gpt4 book ai didi

multithreading - 为什么不能在同一线程上执行多个 pthread_join?

转载 作者:行者123 更新时间:2023-12-02 04:54:26 26 4
gpt4 key购买 nike

来自https://computing.llnl.gov/tutorials/pthreads/ :

A joining thread can match one pthread_join() call. It is a logical error to attempt multiple joins on the same thread.

同样来自“man pthread_join”:

If multiple threads simultaneously try to join with the same thread, the results are undefined.

但是,从程序员的角度来看,多个线程可能希望等待单个线程完成(类似于屏障),这是完全合理的。

例如,我们可能有线程 1、线程 2 独立运行,并且我们可能希望两个线程都等待,直到线程 3 完成。

此限制背后是否有任何技术原因?

最佳答案

我相信技术原因是 pthread_join 是一个 POSIX 标准,对于多线程,它尝试只为实现者指定必要的原语。任何更丰富的语义都会引入更昂贵的实现,并且可能会引入更困难的 API。

事实上,POSIX 已经认为这个函数是一种便利函数,而不是一个原语,它支持一种非常非常常见的用例:一个线程等待另一个线程的终止。

POSIX.1-2008 pthread_join RATIONALE第一段有点长,但提出了许多密切相关的观察结果:

The pthread_join() function is a convenience that has proven useful in multi-threaded applications. It is true that a programmer could simulate this function if it were not provided by passing extra state as part of the argument to the start_routine(). The terminating thread would set a flag to indicate termination and broadcast a condition that is part of that state; a joining thread would wait on that condition variable. While such a technique would allow a thread to wait on more complex conditions (for example, waiting for multiple threads to terminate), waiting on individual thread termination is considered widely useful. Also, including the pthread_join() function in no way precludes a programmer from coding such complex waits. Thus, while not a primitive, including pthread_join() in this volume of POSIX.1-2008 was considered valuable.

关于multithreading - 为什么不能在同一线程上执行多个 pthread_join?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32660041/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com