在 pthread_join() 中阻塞
Blocking in pthread_join()
根据手册页:
The pthread_join() function shall suspend execution of the calling
thread until the target thread terminates, unless the target thread
has already terminated.
因此,据我了解,调用进程将阻塞,直到指定的线程退出。
现在考虑以下代码:
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)
的调用中被阻塞,直到 thrs[0]
以某种方式退出。但是,如果另一个线程,例如,thrs[2]
调用 pthread_exit()
,而我们在对 pthread_join(thrs[0], NULL)
的调用中被阻塞,该怎么办?我们是否必须等待 thrs[0]
退出才能接收 thrs[2]
的 return 值?
是的。代码是串行执行的。
But how if another thread, say thrs[2] exit while we are blocked in
the call to pthread_join(thrs[0], NULL)?
是的,这可能会发生。在这种情况下,pthread_join(thrs[2], NULL);
将立即 return。
Do we have to wait for thrs[0] to exit in order to receive the return
value of thrs[2]?
是的,您必须等待 thr[0]
终止。
(与问题无直接关系)
不必在您创建的每个线程上调用 pthread_join()
。从线程获取 return 状态是一个方便的函数。如果您不需要知道线程的终止状态,您可以
通过查看 "detached" 属性或从线程本身调用 pthread_detach(pthread_self());
来创建线程以使其分离。
在某些情况下,您可能希望创建的线程继续执行但不再需要 main 线程。在这种情况下,您可以从主线程调用 pthread_exit(NULL);
,这将使其他线程即使在主线程退出后也能继续。
是 - 在 thrs[0]
上阻塞的主线程将不会从 thrs[2]
获得结果,直到 thrs[[0]
和 thrs[1]
也退出。
如果您需要更大的灵活性,一种选择是让线程 post 将它们的结果放入队列中,或者以某种其他方式发出线程需要加入的信号。主线程可以监视 queue/signal 并获得必要的结果(这可能来自 pthread_join()
,它在线程上完成,已知从信息 int he queue/signal 完成)。
根据手册页:
The pthread_join() function shall suspend execution of the calling thread until the target thread terminates, unless the target thread has already terminated.
因此,据我了解,调用进程将阻塞,直到指定的线程退出。
现在考虑以下代码:
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)
的调用中被阻塞,直到 thrs[0]
以某种方式退出。但是,如果另一个线程,例如,thrs[2]
调用 pthread_exit()
,而我们在对 pthread_join(thrs[0], NULL)
的调用中被阻塞,该怎么办?我们是否必须等待 thrs[0]
退出才能接收 thrs[2]
的 return 值?
是的。代码是串行执行的。
But how if another thread, say thrs[2] exit while we are blocked in the call to pthread_join(thrs[0], NULL)?
是的,这可能会发生。在这种情况下,pthread_join(thrs[2], NULL);
将立即 return。
Do we have to wait for thrs[0] to exit in order to receive the return value of thrs[2]?
是的,您必须等待 thr[0]
终止。
(与问题无直接关系)
不必在您创建的每个线程上调用 pthread_join()
。从线程获取 return 状态是一个方便的函数。如果您不需要知道线程的终止状态,您可以
通过查看 "detached" 属性或从线程本身调用 pthread_detach(pthread_self());
来创建线程以使其分离。
在某些情况下,您可能希望创建的线程继续执行但不再需要 main 线程。在这种情况下,您可以从主线程调用 pthread_exit(NULL);
,这将使其他线程即使在主线程退出后也能继续。
是 - 在 thrs[0]
上阻塞的主线程将不会从 thrs[2]
获得结果,直到 thrs[[0]
和 thrs[1]
也退出。
如果您需要更大的灵活性,一种选择是让线程 post 将它们的结果放入队列中,或者以某种其他方式发出线程需要加入的信号。主线程可以监视 queue/signal 并获得必要的结果(这可能来自 pthread_join()
,它在线程上完成,已知从信息 int he queue/signal 完成)。