作者psboy (屠牛特攻隊)
看板LinuxDev
標題Re: [問題] pthread的回傳要怎麼寫?
時間Wed Mar 18 20:40:12 2009
: → 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)
推 POSIX:st的char* b 使用時沒malloc, 危險唷~ 03/19 06:32
→ POSIX:這種方法"比較"不好 因為pthread_exit通常用來回報正確與否 03/19 06:32
→ POSIX:但是如果你拿來用成回傳值 也無不妥 只是當你要回傳status 03/19 06:33
→ POSIX:就要另外設計了 03/19 06:33
→ psboy:那有沒有比較好的作法?char * b沒有malloc 那是要怎樣寫? 03/19 09:29
推 POSIX:i mean[ast->b="thread1 hello!"] 你沒malloc char array 03/19 10:38
→ POSIX:danger! 03/19 10:38
推 sunneo:傳struct位址到in比較好 03/19 11:36