使用互斥锁的死锁
在使用互斥锁的多线程 Pthread 程序中会发生死锁。让我们看看如何发生。未锁定的互斥锁由 pthread_mutex_init() 函数初始化。
使用 pthread_mutex_lock() 和 pthread_mutex_unlock() 来获取和释放互斥锁。如果一个线程尝试获取被锁定的互斥锁,则 pthread_mutex_lock() 调用的线程将被阻塞,直到互斥锁的所有者调用 pthread_mutex_unlock()。
我们举个例子,在下面的代码中创建了两个互斥锁 −
/* Create and initialize the mutex locks */ pthread mutex t mutex1; pthread mutex t mutex2; pthread mutex init(&mutex1,NULL); pthread mutex init(&mutex2,NULL);
接下来,创建了两个线程(thread1 和 thread2),这两个线程都可以访问这两个互斥锁。Thread1 和 thread2 分别在函数 dosomework_1 和 dosomework_2 中运行,如下所示 −
/* thread1 runs in this function */ void *dosomework_1(void *param) { pthread mutex lock(&mutex1); pthread mutex lock(&mutex2); /** * Do some work */ pthread mutex unlock(& mutex2); pthread mutex unlock(& mutex2); pthread exit(0); } /* thread2 runs in this function */ void *dosomework_2(void *param) { pthread mutex lock(&mutex2); pthread mutex lock(&mutex1); /** * Do some work */ pthread mutex unlock(&mutex1); pthread mutex unlock(&mutex2); pthread exit(0); }
在这个示例中,thread1 尝试按以下顺序获取互斥锁
- mutex1,
- mutex2,
而 thread two 尝试按以下顺序获取互斥锁
- mutex2,
- mutex1,
如果 thread1 获取 mutex1,而 thread2 获取 mutex2,则可能会发生死锁。即使可能会发生死锁,如果 thread1 可以在 thread2 尝试获取锁之前获取和释放 mutex1 和 mutex2 的互斥锁,则不会发生这种情况。当然,CPU 调度程序会安排线程运行的顺序。上述示例说明了处理死锁所存在的问题:很难识别和测试只在某些调度情况下可能发生的死锁。
广告