【问题标题】:Why pthread_join on itself doesn't result in error or deadlock?为什么 pthread_join 本身不会导致错误或死锁?
【发布时间】:2019-10-20 03:36:08
【问题描述】:

https://repl.it/repls/ColdSilentTriangles

#include <stdio.h>
#include <pthread.h>
pthread_t th;

void *fp(void *args) {
  printf("Thread running...");
  pthread_join(th, NULL);
  printf("Thread waiting...");
  return NULL;
}

int main(void) {
  printf("Hello World\n");
  pthread_create(&th, NULL, fp, NULL);
  pthread_join(th, NULL);
  return 0;
}

来自man pthread_join

pthread_join() 函数暂停调用线程的执行,直到目标线程终止,除非目标线程已经终止。

为什么程序不会导致死锁? 为什么没有产生错误? 为什么 pthread_join() 应该阻塞线程时,屏幕上会输出“Thread waiting...”?

【问题讨论】:

  • 你怎么知道的? pthread_join() 的可能返回值之一是 EDEADLK,但您甚至不检查。
  • 是啊,你说不检查就不会产生错误真的很奇怪。

标签: c multithreading


【解决方案1】:

pthread_join 不会阻止执行,而是在您的示例中返回 EDEADLK

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-09
    • 2019-12-27
    • 1970-01-01
    • 1970-01-01
    • 2011-05-20
    • 1970-01-01
    • 1970-01-01
    • 2020-08-20
    相关资源
    最近更新 更多