/* cc thisfile.c -lthread */ #define _REENTRANT #include #include #define NUM_THREADS 6 static mutex_t Global_mutex; static int Global_data = 0; void *change_global_data(void *); /* for thr_create() */ void *schange_global_data(void *); /* for thr_create() */ main(int argc,char * argv[]) { int i=0; for (i=0; i< NUM_THREADS; i++) { thr_create(NULL, 0, change_global_data, NULL, 0, NULL); } for (i=0; i< NUM_THREADS; i++) { thr_create(NULL, 0, schange_global_data, NULL, 0, NULL); } while ((thr_join(NULL, NULL, NULL) == 0)); } void * change_global_data(void *null) { int i; mutex_lock(&Global_mutex); printf("%d is before \n", i); i=Global_data; printf("%d is after \n", i); Global_data++; sleep(1); printf("%d is global data\n",Global_data); mutex_unlock(&Global_mutex); return NULL; } void * schange_global_data(void *null) { int i; mutex_lock(&Global_mutex); printf("%d is before \n", i); i=Global_data; printf("%d is after \n", i); Global_data--; sleep(1); printf("%d is global data\n",Global_data); mutex_unlock(&Global_mutex); return NULL; }