pthread_join的第二个参数怎么使用?

fibbery 2009-06-01 04:11:56
请给一个具体的例子和输出。谢谢。
...全文
628 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
这是一个分离线程跟普通线程的对比例子,上面有pthread_join的用法对比,你看看吧

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
#include<pthread.h>

void* task1(void*);
void* task2(void*);

void usr();

int p1,p2;

int main()
{
p1=0;
p2=0;
usr();
getchar();
return 1;
}

void usr()
{
pthread_t pid1, pid2;
pthread_attr_t attr;
void *p;
int ret=0;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
pthread_create(&pid1, &attr, task1, NULL);
ret=pthread_join(pid1, &p);
printf("after pthread1:ret=%d,p=%d\n", ret,(int)p);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
if(p2==0)
{ pthread_create(&pid2, &attr, task2, NULL);
p2=1;
}

}


void* task1(void *arg1)
{
printf("task1\n");
pthread_exit( (void *)1);
}

void* task2(void *arg2)
{
int i=0;
printf("thread2 begin.\n");
//pthread_detach(pthread_self());
for(i=0;i<100;i++)
{
sleep(2);
printf("At thread2: i is %d\n",i);
usr();
}
pthread_exit((void *)2);
}
  • 打赏
  • 举报
回复
飞飞,apue上有例子的啊。
mengjfu 2009-06-01
  • 打赏
  • 举报
回复
输出:this is a pthread1.
this is first thread!
hello first!

其中hello first即为返回输出。
mengjfu 2009-06-01
  • 打赏
  • 举报
回复
输出:this is a pthread1.
this is first thread!
hello first!

其中和hello first即为返回输出。
mengjfu 2009-06-01
  • 打赏
  • 举报
回复

#include <stdio.h>

#include <pthread.h>

void thread1(char s[])


{
printf("This is a pthread1.\n");
printf("%s\n",s);
pthread_exit("hello"); //结束线程,返回一个值。
}

/**************main function ****************/

int main(void)


{
pthread_t id1;
void *a1;
int i,ret1;
char s1[]="This is first thread!";
ret1=pthread_create(&id1,NULL,(void *) thread1,s1);

if(ret1!=0){
printf ("Create pthread1 error!\n");
exit (1);
}
pthread_join(id1,&a1);

printf("%s\n",(char*)a1);

return (0);

}
rzsheng 2009-06-01
  • 打赏
  • 举报
回复
http://www.ibm.com/developerworks/cn/linux/thread/posix_threadapi/part4/

23,125

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 应用程序开发区
社区管理员
  • 应用程序开发区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧