Race Condition
A simple example of a race condition is a light switch. In some homes
there are multiple light switches connected to a common ceiling light.
When these types of circuits are used, the switch position becomes irrelevant. If the light is on, moving either switch from its current position turns the light off. Similarly, if the light is off, then moving either switch from its current position turns the light on. With that in mind, imagine what might happen if two people tried to turn on the light using two different switches at exactly the same time. One instruction might cancel the other or the two actions might trip the circuit breaker.
#include<pthread.h>
#include<stdio.h>
void *fun1();
void *fun2();
int shared=1; //shared variable
int main()
{
pthread_t thread1, thread2;
pthread_create(&thread1, NULL,
fun1, NULL);
pthread_create(&thread2, NULL,
fun2, NULL);
pthread_join(thread1, NULL);
pthread_join(thread2,NULL);
printf("Final value of shared
is %d\n",shared); //prints the last updated value of shared variable
}
void *fun1()
{
int x;
x=shared;//thread one reads value of shared variable
x++; //thread one increments its
value
sleep(1); //thread one is preempted
by thread 2
shared=x; //thread one updates the value of shared variable
}
void *fun2()
{
int y;
y=shared;//thread two reads value of shared variable
y--; //thread two increments its
value
sleep(3); //thread two is preempted by thread 1
shared=y; //thread one updates the value of shared variable
}