-1

I'm writing a program in C and which has 3 functions in it, A, B and C. I have a static mutex as global which is locking access to these functions. The functions A, B and C and be called in any order from multithreads so, my code looks as follows:

static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

int A() {
    pthread_mutex_lock(&mutex);
    ... do some processing...
    pthread_mutex_unlock(&mutex);
    return anInt;
}

int B() {
    pthread_mutex_lock(&mutex);
    ... do some processing...
    pthread_mutex_unlock(&mutex);
    return anInt;
}

int C() {
    pthread_mutex_lock(&mutex);
    ... do some processing...
    pthread_mutex_unlock(&mutex);
    return anInt;
}

What might be causing the deadlock?

4

1 回答 1

2

你的代码很干净。

如果我们跳过内存违规的罕见情况等,死锁有两种可能性:

  1. 从这些函数中任何一个的“锁定”部分调用 A()、B() 或 C() 中的任何一个。

  2. 在没有 pthread_mutex_unlock() 的情况下从任何这些函数的“锁定”部分返回。

由于在同一个互斥体上重复调用 pthread_mutex_lock() ,这两种情况都会导致死锁。

对不起,如果我的英语不好:)

于 2013-05-13T13:22:22.470 回答