deadlock.c
· 1.1 KiB · C
Raw
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
pthread_mutex_t lock_a = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t lock_b = PTHREAD_MUTEX_INITIALIZER;
int shared_data = 0;
void* thread_func1(void* arg) {
pthread_mutex_lock(&lock_a);
printf("Thread 1 acquired lock A\n");
shared_data += 1; // 写入共享数据
sleep(1);
pthread_mutex_lock(&lock_b);
printf("Thread 1 acquired lock B\n");
shared_data += 1;
pthread_mutex_unlock(&lock_b);
pthread_mutex_unlock(&lock_a);
return NULL;
}
void* thread_func2(void* arg) {
pthread_mutex_lock(&lock_b);
printf("Thread 2 acquired lock B\n");
shared_data += 1;
sleep(1);
pthread_mutex_lock(&lock_a);
printf("Thread 2 acquired lock A\n");
shared_data += 1;
pthread_mutex_unlock(&lock_a);
pthread_mutex_unlock(&lock_b);
return NULL;
}
int main() {
pthread_t t1, t2;
pthread_create(&t1, NULL, thread_func1, NULL);
pthread_create(&t2, NULL, thread_func2, NULL);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
printf("Done.\n");
return 0;
}
1 | #include <pthread.h> |
2 | #include <stdio.h> |
3 | #include <unistd.h> |
4 | |
5 | pthread_mutex_t lock_a = PTHREAD_MUTEX_INITIALIZER; |
6 | pthread_mutex_t lock_b = PTHREAD_MUTEX_INITIALIZER; |
7 | |
8 | int shared_data = 0; |
9 | |
10 | void* 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 | |
24 | void* 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 | |
39 | int 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 |