UNIX环境高级编程 Figure 11.3

0 篇文章 0 订阅

这是第2版 第11章11.5中的一个例子:

#include "apue.h"
#include <pthread.h>

void *
thr_fn1(void *arg)
{
printf("thread 1 returning/n");
return((void *)1);
}

void *
thr_fn2(void *arg)
{
printf("thread 2 exiting/n");
pthread_exit((void *)2);
}

int
main(void)
{
int err;
pthread_t tid1, tid2;
void *tret;

err = pthread_create(&tid1, NULL, thr_fn1, NULL);
if (err != 0)
err_quit("can't create thread 1: %s/n", strerror(err));
err = pthread_create(&tid2, NULL, thr_fn2, NULL);
if (err != 0)
err_quit("can't create thread 2: %s/n", strerror(err));
err = pthread_join(tid1, &tret);
if (err != 0)
err_quit("can't join with thread 1: %s/n", strerror(err));
printf("thread 1 exit code %d/n", (int)tret);
err = pthread_join(tid2, &tret);
if (err != 0)
err_quit("can't join with thread 2: %s/n", strerror(err));
printf("thread 2 exit code %d/n", (int)tret);
exit(0);
}

执行结果可能如下:
thread 1 returning
thread 2 exiting
thread 1 exit code 1
thread 2 exit code 2
也可能是
thread 1 returning
thread 1 exit code 1
thread 2 exiting
thread 2 exit code 2
注意一点:
这个程序的主线程(执行main函数的逻辑)没有使用sleep函数,也就是说,主线程并不等待thread 1 和thread 2 运行完毕就继续往下执行。
另外,我们不能保证当主线程执行pthread_join时,相应的子线程 thread1 和 thread 2 的状态 (正在执行 或者 执行完毕)
但是,不论你测试多少次,pthread_join总是会正确的返回子线程 thread1 和 thread 2 的结束状态。
这说明,即便子线程 thread1 和 thread 2 已经停止,pthread_join也会取得正确结果。
(如果pthread_join执行时,相应的子线程正在执行, pthread_join会等待子线程执行结束,当然不会有问题!)

关于子线程 thread1 和 thread 2 已经停止时, pthread_join也会取得正确结果。 这点,可以通过在main中添加一个sleep处理证明:
nt

main(void)

{

int err;

pthread_t tid1, tid2;

void *tret;



err = pthread_create(&tid1, NULL, thr_fn1, NULL);

if (err != 0)

err_quit("can't create thread 1: %s/n", strerror(err));

err = pthread_create(&tid2, NULL, thr_fn2, NULL);

if (err != 0)

err_quit("can't create thread 2: %s/n", strerror(err));

sleep(3);

err = pthread_join(tid1, &tret);

if (err != 0)

err_quit("can't join with thread 1: %s/n", strerror(err));

printf("thread 1 exit code %d/n", (int)tret);

err = pthread_join(tid2, &tret);

if (err != 0)

err_quit("can't join with thread 2: %s/n", strerror(err));

printf("thread 2 exit code %d/n", (int)tret);

exit(0);

}

执行结果一定是(除非调试环境很特别hehe):
thread 1 returning
thread 2 exiting
thread 1 exit code 1
thread 2 exit code 2

OK!问题解决。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值