

Printf("Value of shared variable updated by Thread2 is: %d\n",shared) Shared=y //thread2 updates the value of shared variable Sleep(1) //thread2 is preempted by thread 1 Printf("Local updation by Thread2: %d\n",y) Printf("Thread2 reads the value as %d\n",y) Y=shared //thread2 reads value of shared variable

Printf("Value of shared variable updated by Thread1 is: %d\n",shared) Shared=x //thread one updates the value of shared variable Sleep(1) //thread1 is preempted by thread 2 Printf("Local updation by Thread1: %d\n",x) Printf("Thread1 reads the value as %d\n",x) X=shared //thread1 reads value of shared variable Sem_wait(&s) //executes wait operation on s Printf("Final value of shared is %d\n",shared) //prints the last updated value of shared variable Pthread_create(&thread2, NULL, fun2, NULL) Pthread_create(&thread1, NULL, fun1, NULL) Sem_init(&s,0,1) //initialize semaphore variable - 1st argument is address of variable, 2nd is number of processes sharing semaphore, 3rd argument is the initial value of semaphore variable Both the threads make use of semaphore variable so that only one of the threads is executing in its critical section #include Program creates two threads: one to increment the value of a shared variable and second to decrement the value of the shared variable. Program 1: Program for process synchronization using semaphores Here, we write a Program for Process Synchronization using Semaphores to understand the implementation of sem_wait() and sem_signal() to avoid a race condition. In C program the corresponding operations are sem_wait() and sem_post(). Semaphore is an integer variable which is accessed or modified by using two atomic operations: wait() and signal().
