这是第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!问题解决。