我有一个问题。
我初始化了一个静态互斥锁,并试图在我的所有函数中锁定它。 我不小心忘记在其中一个函数中解锁它,但是当我调用另一个也试图获取互斥锁的函数时,似乎没有发生死锁。
有人可以解释一下为什么不会发生死锁吗?
解释我的问题场景的代码:
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/