Last active 1749041370

Revision 66a10ade0747aa94c09b74a9d8d5b9638a8473ed

deadlock.c Raw
1#include <pthread.h>
2#include <stdio.h>
3#include <unistd.h>
4
5pthread_mutex_t lock_a = PTHREAD_MUTEX_INITIALIZER;
6pthread_mutex_t lock_b = PTHREAD_MUTEX_INITIALIZER;
7
8int shared_data = 0;
9
10void* thread_func1(void* arg) {
11 pthread_mutex_lock(&lock_a);
12 printf("Thread 1 acquired lock A\n");
13 shared_data += 1; // 写入共享数据
14 sleep(1);
15 pthread_mutex_lock(&lock_b);
16 printf("Thread 1 acquired lock B\n");
17 shared_data += 1;
18
19 pthread_mutex_unlock(&lock_b);
20 pthread_mutex_unlock(&lock_a);
21 return NULL;
22}
23
24void* thread_func2(void* arg) {
25 pthread_mutex_lock(&lock_b);
26 printf("Thread 2 acquired lock B\n");
27 shared_data += 1;
28 sleep(1);
29 pthread_mutex_lock(&lock_a);
30 printf("Thread 2 acquired lock A\n");
31 shared_data += 1;
32
33 pthread_mutex_unlock(&lock_a);
34 pthread_mutex_unlock(&lock_b);
35 return NULL;
36}
37
38
39int main() {
40 pthread_t t1, t2;
41
42 pthread_create(&t1, NULL, thread_func1, NULL);
43 pthread_create(&t2, NULL, thread_func2, NULL);
44
45 pthread_join(t1, NULL);
46 pthread_join(t2, NULL);
47
48 printf("Done.\n");
49 return 0;
50}
51