作者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)
1F:推 POSIX:st的char* b 使用时没malloc, 危险唷~ 03/19 06:32
2F:→ POSIX:这种方法"比较"不好 因为pthread_exit通常用来回报正确与否 03/19 06:32
3F:→ POSIX:但是如果你拿来用成回传值 也无不妥 只是当你要回传status 03/19 06:33
4F:→ POSIX:就要另外设计了 03/19 06:33
5F:→ psboy:那有没有比较好的作法?char * b没有malloc 那是要怎样写? 03/19 09:29
6F:推 POSIX:i mean[ast->b="thread1 hello!"] 你没malloc char array 03/19 10:38
7F:→ POSIX:danger! 03/19 10:38
8F:推 sunneo:传struct位址到in比较好 03/19 11:36