pthreads - 为什么 pthread_join() 不会造成死锁?

标签 pthreads pthread-join

下面是我希望程序陷入死锁的程序,因为 pthread_join() 是线程上的阻塞等待(它正在等待终止)。

但我看到 pthread_join() 不会阻塞并返回失败 (35 = EDEADLK)

你能帮我理解为什么 pthread_join() 会解除阻塞吗?因为主线程尚未终止,这可能应该是一个死锁?

#include <stdio.h>

#include <stdlib.h>
#include <pthread.h>

int
main(int argc, char *argv[])
{
    void *res;
    int s;
    printf("Message from main()\n");

    s = pthread_join(pthread_self(), &res);
    if (s != 0)
        printf("pthread_join(): %d",s);
        
    printf("Thread returned %d\n", (int) res);
    exit(0);
}

这是输出:

Message from main()
pthread_join(): 35
Thread returned 134514009

最佳答案

您无法加入自己。 POSIX manpage for pthread_join指定您可能会收到死锁错误:

[EDEADLK]
    A deadlock was detected or the value of thread specifies the calling thread.

事实上,对该错误的搜索表明它是 35,至少在我的系统上是这样:

pax> cd /usr/include
pax> grep EDEADLK *.h */*.h */*/*.h
asm-generic/errno.h:#define EDEADLK     35  /* Resource deadlock would occur */

虽然一些死锁很微妙并且难以让 pthread 自动检测到,但这个死锁相对容易,在 join 函数的开头有这样的内容:

int pthread_join(pthread_t thread, void **value_ptr) {
    if (thread == pthread_self())
        return EDEADLK;
    // rest of function
}

关于pthreads - 为什么 pthread_join() 不会造成死锁?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24094855/

相关文章:

c - POSIX 是否保证信号不会传递给部分初始化的线程?

c - Pthreads 在执行时更新全局 2D 数组段错误

c - pthread_join 不影响主线程

c - 如何使用 pthread_cancel 避免内存泄漏?

c - 线程加入后,结构内的数组在 C 中被销毁

c++ - C++ 中的高效线程安全单例

c++ - Pthread + Visual Studio 2013 编译错误

c - pthread 完成后打印变量

c - pthread mutex 在 macOS 上无法正常工作

c - ·等待C中各个线程中的第一个