gpt4 book ai didi

c - 多次调用 pthread_join 如何工作?

转载 作者:太空宇宙 更新时间:2023-11-04 01:03:47 27 4
gpt4 key购买 nike

我正在重新开始使用 pthreads,而 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. On return from a successful pthread_join() call with a non-NULL value_ptr argument, the value passed to pthread_exit() by the terminating thread shall be made available in the location referenced by value_ptr. When a pthread_join() returns successfully, the target thread has been terminated. The results of multiple simultaneous calls to pthread_join() specifying the same target thread are undefined. If the thread calling pthread_join() is canceled, then the target thread shall not be detached."

我试图理解,如果我为一个线程调用 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;
}

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

我真的很想了解它是如何工作的。

提前致谢。

最佳答案

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

关于c - 多次调用 pthread_join 如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29039697/

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