Why it is problematic to use mutex locks within signal handers?

Naf*_*aly 3 c multithreading mutex deadlock signals

Below is the pseudo code in question:

int c;
pthread_mutex_t mtx;


void inc(int count)
{
    pthread_mutex_lock(&mtx);
    c += count;
    pthread_mutex_unlock(&mtx);
}


int main(void)
{
    pthread_mutex_init(&mtx);
    signal(SIGUSR1, inc);
    signal(SIGUSR2, inc);
    sleep(100000); // Sleep for long enough
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

How and why can this code could lead to a deadlock?

Why this is different to the following scenario:

  1. Thread 1 acquires the mutex.
  2. Context switch is made and Thread 2 tries to get the lock and put on waiting list.
  3. 线程 1 完成并释放锁。
  4. 线程 2 唤醒并继续执行。
  5. 没有死锁。

pil*_*row 6

您的信号处理程序都将在同一个线程中运行。如果在第一个信号的处理程序锁定互斥锁时第二个信号到达,您的单独线程将再次尝试锁定互斥锁和死锁:

time    thread 0
----    --------
  0      main:...
  1      main:sleep()
 ...     ...
 100     <<SIGUSR1>>
 101     inc:pthread_mutex_lock()
 102     inc:count += ...
 103     <<SIGUSR2>>
 104     inc:pthread_mutex_lock()  // deadlock
Run Code Online (Sandbox Code Playgroud)