分类: C/C++
2012-01-17 13:21:49
实例:
/*myfile11-3.c*/
#include
#include
#include
pthread_t tid1, tid2;
void *tret;
void *
thr_fn1(void *arg)
{
sleep(1);//睡眠一秒,等待TID2结束。
pthread_join(tid2, &tret);//tid1一直阻赛,等到tid2的退出,获得TID2的退出码
printf("thread 2 exit code %d\n", (int)tret);
printf("thread 1 returning\n");
return((void *)2);
}
void *
thr_fn2(void *arg)
{
printf("thread 2 exiting\n");
pthread_exit((void *)3);
}
int
main(void)
{
int err;
err = pthread_create(&tid1, NULL, thr_fn1, NULL);
if (err != 0)
printf("can't create thread 1\n");
err = pthread_create(&tid2, NULL, thr_fn2, NULL);
if (err != 0)
printf("can't create thread 2\n");
err = pthread_join(tid1, &tret);//祝线程一直阻赛,等待TID1的返回。
if (err != 0)
printf("can't join with thread 1\n");
printf("thread 1 exit code %d\n", (int)tret);
//err = pthread_join(tid2, &tret);
//if (err != 0)
// printf("can't join with thread 2\n");
// printf("thread 2 exit code %d\n", (int)tret);
exit(0);
}
命令:#gcc -lthread myfile11-3.c
:#./a.out
运行结果:
thread 2 exiting
thread 2 exit code 3
thread 1 returning
thread 1 exit code 2