根据手册页:
pthread_join() 函数应暂停调用的执行
线程直到目标线程终止,除非目标线程
已经终止了。
因此,据我了解,调用进程将阻塞,直到指定的线程退出。
现在考虑以下代码:
pthread_t thrs[NUMTHREADS];
for (int i = 0; i < NUMTHREADS; i++)
{
pthread_create(&thrs[i], NULL, thread_main, NULL);
}
pthread_join(thrs[0], NULL); /* will be blocked here */
pthread_join(thrs[1], NULL);
pthread_join(thrs[2], NULL);
/* ... */
pthread_join(thrs[NUMTHREADS - 1], NULL);
调用线程将被阻塞在调用中pthread_join(thrs[0], NULL)
, until thrs[0]
以某种方式退出。但是,如果另一个线程,例如,thrs[2]
call pthread_exit()
当我们打电话受阻时pthread_join(thrs[0], NULL)
?我们必须等待吗thrs[0]
退出以接收返回值thrs[2]
?
但是,如果另一个线程(例如 thrs[2])在我们被阻塞时退出怎么办?
对 pthread_join(thrs[0], NULL) 的调用?
是的,这有可能发生。在这种情况下,pthread_join(thrs[2], NULL);
将立即返回。
我们是否必须等待 thrs[0] 退出才能收到返回
thrs[2] 的值?
是的,你必须等待thr[0]
终止。
(与问题没有直接关系)
没有必要打电话pthread_join()
在您创建的每个线程上。这是一个从线程获取返回状态的便捷函数。如果您不需要知道线程的终止状态,您可以
通过查看“detached”属性或调用来创建线程pthread_detach(pthread_self());
从线程本身,使其分离。
在某些情况下,您希望创建的线程继续执行,但不再需要main线。在这种情况下,您可以致电pthread_exit(NULL);
来自主线程,这将使其他线程即使在主线程退出后也可以继续。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)