File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments