Re: [問題] pthread的回傳要怎麼寫?
: → hpeter:pthread_join & pthread_exit 03/18 00:12
: → psboy:不過問題又來了 如果是回傳一堆資料怎麼辦?傳址似乎會出鎚 03/18 11:27
: → psboy:原來一開始就傳struct進去在thread裏面設定好回傳值就好了xD 03/18 16:49
: → hpeter:可以試試在 thread 裡 malloc 一個struct 用 pthread_exit 03/18 20:02
: → hpeter:回傳 address XD 03/18 20:02
試著用malloc一個struct的方法可行 :D
以下是亂改的code xD
#include <stdio.h>
#include <pthread.h>
struct st
{
int a;
char * b;
};
void * thread1(void * in)
{
char * s=(char *)in;
printf("This is a pthread1.\n");
printf("%s\n",s);
struct st * ast;
ast=malloc(sizeof(struct st));
ast->a=111;
ast->b="thread1 hello!";
pthread_exit(ast);
}
void * thread2(void * in)
{
char * s=(char *) in;
printf("This is a pthread2.\n");
printf("%s\n",s);
struct st * bnd;
bnd=malloc(sizeof(struct st));
bnd->a=222;
bnd->b="thread2 hello!";
pthread_exit(bnd);
}
/**************main function ****************/
int main(void)
{
pthread_t id1,id2;
void *a1,*a2;
int i,ret1,ret2;
char s1[]="This is first thread!";
char s2[]="This is second thread!";
ret1=pthread_create(&id1,NULL,(void *) thread1,s1);
ret2=pthread_create(&id2,NULL,(void *) thread2,s2);
if(ret1!=0){
printf ("Create pthread1 error!\n");
exit (1);
}
pthread_join(id1,&a1);
struct st * tmp;
tmp=(struct st *) a1;
printf("thread1 return int a:%d,string b:%s\n",tmp->a,tmp->b);
if(ret2!=0){
printf ("Create pthread2 error!\n");
exit (1);
}
printf("This is the main process.\n");
pthread_join(id2,&a2);
tmp=(struct st *) a2;
printf("thread2 return int a:%d,string b:%s\n",tmp->a,tmp->b);
}
-
至於變數為啥是ast跟bnd
原本是用1st跟2nd
compiler不給過 xD
所以才偷改一個字 Or2
也有人跟我說
一開始就傳struct位址進去
似乎也是個辦法
不知道用那種比較好?
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 219.87.143.66
※ 編輯: psboy 來自: 219.87.143.66 (03/18 20:45)
推
03/19 06:32, , 1F
03/19 06:32, 1F
→
03/19 06:32, , 2F
03/19 06:32, 2F
→
03/19 06:33, , 3F
03/19 06:33, 3F
→
03/19 06:33, , 4F
03/19 06:33, 4F
→
03/19 09:29, , 5F
03/19 09:29, 5F
推
03/19 10:38, , 6F
03/19 10:38, 6F
→
03/19 10:38, , 7F
03/19 10:38, 7F
推
03/19 11:36, , 8F
03/19 11:36, 8F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 2 篇):
LinuxDev 近期熱門文章
PTT數位生活區 即時熱門文章