[Linux] An article to fix the deadlock of multi-threaded programming

1. Two situations of deadlock

  • Two situations:
  1. In 多线程the program, 多个线程使用同一个互斥锁时which 一个线程``拿到了互斥锁then, however 一直不释放互斥锁, lead to 其他线程一直阻塞internal locking function, this phenomenon is 死锁a phenomenon
  2. In the 多线程program, there 两个互斥锁are mutex lock A and mutex lock B respectively in the program. The program is running, 线程1got it 互斥锁A, 线程Bgot it 互斥锁B, the 都不释放respective mutex locks of thread 1 and thread 2 , and also want to apply for them 拿对方的互斥锁. 都阻塞This phenomenon is also a 死锁phenomenon when the thread is inside the function holding each other's mutex lock

2. Simulate deadlock program

  • Thread 1 gets the mutex lock A and never releases the mutex lock A
  • Thread 2 gets the mutex lock B and never releases the mutex lock B
  • Thread 1 applies for mutex lock B
  • Thread 2 applies for mutex lock A
  • Both threads are 阻塞in lock_wait in the pthread_mutex_lock function
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>

pthread_mutex_t lockA = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t lockB = PTHREAD_MUTEX_INITIALIZER;

void* task1(void* arg)                                    
{
    
    
  pthread_mutex_lock(&lockA);
  sleep(2); //防止一个线程执行过快 把锁都拿到了
  pthread_mutex_lock(&lockB);
    
  return NULL;
}
void* task2(void* arg)
{
    
    
  pthread_mutex_lock(&lockB);
  sleep(2);
  pthread_mutex_lock(&lockA);
    
  return NULL;
}

int main()
{
    
    
  pthread_t thread1,thread2;

  int ret_th1 = pthread_create(&thread1,NULL,task1,NULL);
  int ret_th2 = pthread_create(&thread2,NULL,task2,NULL);
  if(ret_th1<0 && ret_th2<0)
  {
    
    
    perror("pthread_create");
    return -1;
  }

  pthread_join(thread1,NULL);
  pthread_join(thread2,NULL);
  pthread_mutex_destroy(&lockA);
  pthread_mutex_destroy(&lockB);

  return 0;
}

3. Program call stack information

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_45437022/article/details/112404979