Last active 1749041370

anduin's Avatar anduin revised this gist 1749041370. Go to revision

1 file changed, 3 insertions

deadlock.c

@@ -1,3 +1,6 @@
1 + // gcc -g ./s.c -o deadlock_demo -lpthread
2 + // sudo valgrind --tool=helgrind ./deadlock_demo
3 +
1 4 #include <pthread.h>
2 5 #include <stdio.h>
3 6 #include <unistd.h>

anduin's Avatar anduin revised this gist 1749041345. Go to revision

1 file changed, 50 insertions

deadlock.c(file created)

@@ -0,0 +1,50 @@
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 + }
Newer Older