如何多次调用pthread_join?

时间:2015-03-13 18:43:10

标签: c multithreading

我正在重新使用pthreads并且pthread_join的定义困扰我。

它说

  

“pthread_join()函数应暂停执行调用   线程直到目标线程终止,除非是目标线程   已经终止了。从成功的pthread_join()返回   使用非NULL value_ptr参数调用,传递给的值   终止线程的pthread_exit()应该可用   value_ptr引用的位置。当pthread_join()返回时   成功,目标线程已终止。结果   多个同时调用pthread_join()指定相同的   目标线程未定义。如果调用pthread_join()的线程是   取消,然后目标线程不得分离。“

我试图理解,如果我为一个线程调用pthread_join,然后调用pthread_join启动第二个线程,则启动两个线程,即使我想,第二个pthread_join也无法调用,因为第一个连接已暂停执行的主线程,并运行下一行,直到从连接的线程中调用pthread_exit。

特别是,我想,第一个pthread_join必须等到指定的线程调用pthread_exit,然后它才会继续。但事实并非如此,正如我所能做的那样:

#include <pthread.h>
#include <stdio.h>

int avail = 0;

void *consumer(void *unused)
{
    while (1) {
        if (avail > 0) {
            --avail;
            puts("consumed");
        }
    }
}

void *producer(void *unused)
{
    while (1) {
        ++avail;
        puts("produced");
    }
}

int main(int argc, char **argv)
{
    pthread_t c_thread;
    pthread_t p_thread; 
    pthread_create(&c_thread, 0, consumer, 0);
    pthread_create(&p_thread, 0, producer, 0);
    pthread_join(c_thread, 0);
    pthread_join(p_thread, 0);

    return 0;
}

忽略可能的竞争条件试图减少代码大小的问题,为什么两个线程都在工作,尽管第一个连接暂停主线程(因此,在我看来,阻止调用下一个连接)。

我真的很想了解这是如何运作的。

提前致谢。

2 个答案:

答案 0 :(得分:5)

线程同时运行,在调用pthread_create期间或之后的某个时间开始。调用pthread_join与启动或运行线程无关,它只是等待它退出。您的两个线程都已经运行,并且在您输入的位置仍然可以运行并阻塞第一个连接,它们将继续运行。第一次加入阻止的唯一事情是你的主线程。

答案 1 :(得分:0)

线程不是在pthread_join中启动,而是在pthread_create中启动。我误以为自己认为pthread_join用于实际启动线程,而在主线程继续执行之前,特定线程返回非繁忙等待,在我的情况下,在线程获得之前主要返回有机会调用看跌期权函数。

我的代码中的第二个pthread_join实际上从未被调用,因为main确实从第一个pthread_join暂停,等待c_thread返回。在这个特定场景中的第二个连接是&#34;无操作&#34;而且程序实际上从未实现过,因为消费者永远不会真正返回。