下面是我希望程序陷入死锁的程序,因为 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/