【问题标题】:Waiting of Semaphores in the pthread API在 pthread API 中等待信号量
【发布时间】:2011-09-04 16:51:03
【问题描述】:

如果一个信号量值为 0 并且你等待它,我一直认为线程阻塞。 为什么下面的代码没有阻塞。

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

sem_t sA;

void* funcA(void* param) {
  sem_wait(&sA);
  printf("Thread A\n");
  pthread_exit(0);
}

int main() {
  sem_init(&sA, 0, 0);
  pthread_t tA;
  pthread_create(&tA, NULL, funcA, NULL);
  pthread_exit(0);
  sem_destroy(&sA);
  return 0;
}

【问题讨论】:

  • “i686-apple-darwin10-gcc-4.2.1 (GCC) 4.2.1 (Apple Inc. build 5664)”。如果有帮助的话。
  • 顺便说一句,pthread_exit() 之后的任何代码都是死代码。该函数不返回。

标签: pthreads semaphore


【解决方案1】:

来自 man sem_destroy:

   Destroying  a  semaphore  that other processes or threads are currently
   blocked on (in sem_wait(3)) produces undefined behavior.

看起来您的实现和我的实现对如何处理这种未定义的行为采取了不同的选择。什么都行。

【讨论】:

  • 对!但是 main() 中的 pthread_exit 会阻塞,直到 ThreadA 完成。
  • pthread_exit 不会那样阻塞,它只是终止线程。 pthread_join 将阻塞直到另一个线程完成 if 它被创建以便可连接。 @Mat 有一个很好的观点,尽管 sem_destory 调用永远不会受到打击。
  • 哦...我明白了。学到了一些东西。你是对的,sem_destroy 从来没有被调用过,所以我不认为这是问题所在。您的机器上的线程是否被阻塞?
  • 是的,这里被阻塞了。不过,除了推测之外,我真的无能为力。我会有更多的想法
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-05-28
  • 2018-02-07
  • 2012-04-12
  • 1970-01-01
  • 2016-06-21
  • 2014-10-21
  • 1970-01-01
相关资源
最近更新 更多