Skip to content

Commit 8fc1bf9

Browse files
committed
none
1 parent a4f89a5 commit 8fc1bf9

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

ch14/deadlock.cpp

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
#include <pthread.h>
2+
#include <unistd.h>
3+
#include <stdio.h>
4+
5+
int a = 0;
6+
int b = 0;
7+
pthread_mutex_t mutex_a;
8+
pthread_mutex_t mutex_b;
9+
10+
void* another( void* arg ){
11+
pthread_mutex_lock( &mutex_b );
12+
printf("in child thread, got mutex b, waiting for mutex a\n");
13+
sleep( 5 );
14+
++b;
15+
pthread_mutex_lock( &mutex_a );
16+
b += a++;
17+
pthread_mutex_unlock( &mutex_a );
18+
pthread_mutex_unlock( &mutex_b );
19+
pthread_exit( NULL );
20+
}
21+
22+
int main(){
23+
pthread_t id;
24+
25+
pthread_mutex_init( &mutex_a, NULL );
26+
pthread_mutex_init( &mutex_b, NULL );
27+
pthread_create( &id, NULL, another, NULL );
28+
29+
pthread_mutex_lock( &mutex_a );
30+
printf("in parent thread, got mutex a, waiting for mutex b\n");
31+
sleep(5);
32+
++a;
33+
pthread_mutex_lock( &mutex_b );
34+
a += b++;
35+
pthread_mutex_unlock( &mutex_b );
36+
pthread_mutex_unlock( &mutex_a );
37+
38+
pthread_join( id, NULL );
39+
pthread_mutex_destroy( &mutex_a );
40+
pthread_mutex_destroy( &mutex_b );
41+
return 0;
42+
}

0 commit comments

Comments
 (0)