死锁现象
当多个线程中为了保护多个共享资源而使用了多个互斥锁,如果多个互斥锁使用不当,就可能造成,多个线程一直等待对方的锁释放,这就是死锁现象。

代码演示:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<pthread.h>
#include<fcntl.h>
#include <sys/stat.h>
#include <errno.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <mqueue.h>
pthread_mutex_t mtx1;
pthread_mutex_t mtx2;
void *thread(void* arg) {
printf("子线程获取mtx1中。。。\n");
pthread_mutex_lock(&mtx1);
printf("子线程成功获取mtx1\n");
sleep(1);
printf("子线程获取mtx2中。。。\n");
pthread_mutex_lock(&mtx2);
printf("子线程成功获取mtx2\n");
pthread_mutex_unlock(&mtx2);
pthread_mutex_unlock(&mtx1);
}
int main(int argc, char*argv[]){
pthread_mutex_init(&mtx1, NULL);
pthread_mutex_init(&mtx2, NULL);
pthread_t tid;
pthread_create(&tid, NULL, thread, NULL);
printf("主线程获取mtx2中。。。\n");
pthread_mutex_lock(&mtx2);
printf("主线程成功获取mtx2\n");
sleep(1);
printf("主线程获取mtx1中。。。\n");
pthread_mutex_lock(&mtx1);
printf("主线程成功获取mtx1\n");
pthread_mutex_unlock(&mtx1);
pthread_mutex_unlock(&mtx2);
pthread_exit(NULL);
pthread_join(tid, NULL);
pthread_mutex_destroy(&mtx1);
pthread_mutex_destroy(&mtx2);
}
结果:
对于子线程来说,先成功的获取到了mtx1,随后会获取mtx2,但是mtx2现在已经被主线程获取到了,所以从代码上来看只要主线程结束后,mtx2就会被解锁,但是对于主线程来说,mtx2获取完了,接下来是要尝试获取mtx1的,但是同样mtx1此时已经被子线程获取了,也就是主线程得等待子线程结束后mtx1才会被解锁,从而被主线程尝试获取,这样的话,情况就变成了两个线程相互等待对面进程结束从而继续进行自己的代码,成了一个环,所以执行不了,本质上就是两个互斥锁的使用不当,此时现象就叫做死锁现象。