现象:我先创建两个线程 A和B,将其线程ID保存下来。 然后依次pthread_join 这两个线程。然后创建一个新的线程C。
然后我再次pthread_join 线程A和B。 结果发现他们两个之中一个会返回成功。
原因:
因为线程C的线程ID和线程A和B之中的一个相同。导致我对同一个线程pthread_join 两次,分别pthread_join 了不同的线程。
措施:
在调用pthread_join 的时候进行判断是否已经pthread_join 了,如果已经joni了,就不再join。如果这样做则需要考虑多线程同时访问。
man pthread_join :有如下提示
After a successful call to pthread_join(), the caller is guaranteed that the target thread has terminated.
Joining with a thread that has previously been joined results in undefined behavior.
All of the threads in a process are peers: any thread can join with any other thread in the process.