c - posix 互斥锁没有按预期工作

标签 c linux pthreads mutex

我有一个问题。

我初始化了一个静态互斥锁,并试图在我的所有函数中锁定它。 我不小心忘记在其中一个函数中解锁它,但是当我调用另一个也试图获取互斥锁的函数时,似乎没有发生死锁。

有人可以解释一下为什么不会发生死锁吗?

解释我的问题场景的代码:

 pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

 void main(void)
 {
   func1();  // Mutex acquired initially but not released at end
   func2();  // This function acquires mutex even though mutex was not released by func1();

 }


 void func1(void)
 {
   pthread_mutex_lock(&mutex);

   printf("I am in func1\n");

   //MUTEX NOT UNLOCKED
 }

 void func2(void)
 {
   pthread_mutex_lock(&mutex);

   printf("I am in func2\n");

   //MUTEX AGAIN NOT UNLOCKED
 }

谁能解释一下为什么 func2() 中没有发生死锁,因为 func1() 中没有释放互斥量?

最佳答案

根据规范,PTHREAD_MUTEX_INITIALIZER 相当于一个默认的互斥体:

In cases where default mutex attributes are appropriate, the macro PTHREAD_MUTEX_INITIALIZER can be used to initialise mutexes that are statically allocated. The effect is equivalent to dynamic initialisation by a call to pthread_mutex_init() with parameter attr specified as NULL, except that no error checks are performed.

对于默认的互斥量,试图锁定已被调用线程锁定的互斥量会导致未定义的行为:

If the mutex type is PTHREAD_MUTEX_DEFAULT, attempting to recursively lock the mutex results in undefined behaviour.

关于c - posix 互斥锁没有按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11917692/

相关文章:

regex - 这个awk语句是什么意思?

linux - 卷起/遮挡 float 窗口真棒?

c - 如何同步对数组索引的访问

gdb:找不到新线程:系统更新后出现一般错误

c - C 中的 TCP/IP 简单文件服务器在 C 中读取服务器上的问题

c - Malloc、free 和段错误

linux - xargs - 程序是循环运行还是重新执行

c - 使用单词作为 strtok 的分隔符?

c - C/C++ 中的单行 #ifdef

c - 在哪些系统上 sleep() 不是 pthread 取消点?