11#include <stdio.h>
2+ #include <stdlib.h>
23#include <string.h>
34#include <pthread.h>
45
6+ #define NUM_THREADS 10
7+
58//
69// Created by Emmanuel Massaquoi on 6/19/17.
710//
811
912int shared_var = 0 ;
10- int resource_use = 0 ;
13+ int resource_use ;
14+ int num_reader = 0 ;
15+
16+ int reading = 0 ;
17+ int writing = 1 ;
1118
1219pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER ;
1320pthread_cond_t read_phase = PTHREAD_COND_INITIALIZER ;
@@ -19,7 +26,29 @@ void *writer (void *param);
1926
2027int main (int argc , char * argv []) {
2128
22- printf ("Hello World/m" );
29+ pthread_t tid [NUM_THREADS ];
30+
31+ for (int i = 0 ; i < 5 ; i ++ ) {
32+
33+ printf ("Create Reader\n" );
34+ if (pthread_create (& tid [i ], NULL , reader , NULL ) != 0 ) {
35+ fprintf (stderr , "Unable to create reader thread" );
36+ exit (1 );
37+ }
38+
39+ printf ("Create Writer\n" );
40+ if (pthread_create (& tid [i + 5 ], NULL , writer , NULL ) != 0 ) {
41+ fprintf (stderr , "Unable to create writer thread" );
42+ exit (1 );
43+ }
44+ }
45+
46+ for (int j = 0 ; j < NUM_THREADS ; ++ j ) {
47+ pthread_join (tid [j ], NULL );
48+ }
49+
50+ printf ("Parent quiting\n" );
51+
2352 return 0 ;
2453}
2554
@@ -29,10 +58,39 @@ void *reader(void *param) {
2958
3059 pthread_mutex_lock (& m );
3160
32- while (resource_use == 1 ) {
61+ while (resource_use == writing ) {
3362 pthread_cond_wait (& read_phase , & m );
3463 }
3564
65+ printf ("Reader Value: %d\n" , shared_var );
66+ printf ("Number of Readers Present: %d\n" , num_reader );
67+
68+ resource_use = reading ;
69+ pthread_cond_broadcast (& write_phase );
70+
71+ pthread_mutex_unlock (& m );
72+ }
73+
74+ return 0 ;
75+ }
76+
77+ void * writer (void * param ) {
78+
79+ for (int i = 1 ; i <= 20 ; ++ i ) {
80+ pthread_mutex_lock (& m );
81+
82+ while (resource_use == reading || num_reader != 0 ) {
83+ pthread_cond_wait (& write_phase , & m );
84+ }
85+
86+ shared_var = i ;
87+ printf ("Written Value: %d\n" , shared_var );
88+ printf ("Number of Readers Present: %d\n" , num_reader );
89+
90+ resource_use = writing ;
91+ pthread_cond_broadcast (& read_phase );
92+
3693 pthread_mutex_unlock (& m );
3794 }
95+
3896}
0 commit comments