给我一个能直观看出死锁了的c语言代码
时间: 2023-06-12 19:06:32 浏览: 101
死锁的检测与接触 C语言
以下是一个简单的 C 语言程序,演示了如何出现死锁:
```c
#include <stdio.h>
#include <pthread.h>
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER;
void* func1(void* arg) {
pthread_mutex_lock(&mutex1);
printf("Thread 1 acquired mutex1\n");
sleep(1);
pthread_mutex_lock(&mutex2);
printf("Thread 1 acquired mutex2\n");
pthread_mutex_unlock(&mutex2);
pthread_mutex_unlock(&mutex1);
return NULL;
}
void* func2(void* arg) {
pthread_mutex_lock(&mutex2);
printf("Thread 2 acquired mutex2\n");
sleep(1);
pthread_mutex_lock(&mutex1);
printf("Thread 2 acquired mutex1\n");
pthread_mutex_unlock(&mutex1);
pthread_mutex_unlock(&mutex2);
return NULL;
}
int main() {
pthread_t thread1, thread2;
pthread_create(&thread1, NULL, func1, NULL);
pthread_create(&thread2, NULL, func2, NULL);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
return 0;
}
```
该程序启动两个线程,每个线程都需要锁定两个互斥锁,但它们的锁定顺序相反。这样,当第一个线程锁定 mutex1 并等待 mutex2,而第二个线程锁定 mutex2 并等待 mutex1 时,它们就会陷入死锁状态。如果您在运行此程序时观察到它永远不会退出,请检查它是否陷入了死锁状态。
阅读全文