/* Coded By Karthik Ananthapadmanaban 9:55 PM 9/27/2007 */ #include #include sem_t sem1; int global=0; void * threaded_fn(void *g) { int j; //p was 1 when thread was created. Now its decremented to 0, so 1 thread blocks and //1 proceeds sem_wait(&sem1); printf("\n %d processing...",pthread_self()); sem_getvalue(&sem1,&j); printf("\n Value of sem1 is %d",j); for(j=0;j<100;j++) global++; printf("\n The value of global is %d",global); if(global==100){ sleep(5); } //Increment p by 1 so that 2nd thread gets a chance! sem_post(&sem1); sem_getvalue(&sem1,&j); printf("\n Value of sem1 now is %d",j); } int main() { pthread_t pth[2]; int i=0,j; sem_init(&sem1,0,0); //Increments parameter 3 in sem_init to 1, let param 3 be p sem_post(&sem1); sem_getvalue(&sem1,&j); printf("\n Value of sem1 is %d",j); for(i=0;i<2;i++) pthread_create(&pth[i],NULL,threaded_fn,NULL); for(i=0;i<2;i++) pthread_join(pth[i],NULL); printf("\n Processes done..."); return 0; }