Race Condition, Critical Section and Semaphore


Race conditions, Critical Sections and Semaphores are an key part of Operating systems. Details about these are given as follows −

Race Condition

A race condition is a situation that may occur inside a critical section. This happens when the result of multiple thread execution in critical section differs according to the order in which the threads execute.

Race conditions in critical sections can be avoided if the critical section is treated as an atomic instruction. Also, proper thread synchronization using locks or atomic variables can prevent race conditions.

Critical Section

The critical section in a code segment where the shared variables can be accessed. Atomic action is required in a critical section i.e. only one process can execute in its critical section at a time. All the other processes have to wait to execute in their critical sections.

The critical section is given as follows:

do{
   Entry Section
   Critical Section
   Exit Section
   Remainder Section
} while (TRUE);

In the above diagram, the entry sections handles the entry into the critical section. It acquires the resources needed for execution by the process. The exit section handles the exit from the critical section. It releases the resources and also informs the other processes that critical section is free.

The critical section problem needs a solution to synchronise the different processes. The solution to the critical section problem must satisfy the following conditions −

  • Mutual Exclusion

    Mutual exclusion implies that only one process can be inside the critical section at any time. If any other processes require the critical section, they must wait until it is free.

  • Progresss

    Progress means that if a process is not using the critical section, then it should not stop any other process from accessing it. In other words, any process can enter a critical section if it is free.

  • Bounded Waitings

    Bounded waiting means that each process must have a limited waiting time. Itt should not wait endlessly to access the critical section.

Semaphore

A semaphore is a signalling mechanism and a thread that is waiting on a semaphore can be signalled by another thread. This is different than a mutex as the mutex can be signalled only by the thread that called the wait function.

A semaphore uses two atomic operations, wait and signal for process synchronization.

The wait operation decrements the value of its argument S, if it is positive. If S is negative or zero, then no operation is performed.

wait(S){
   while (S<=0);
   S--;
}

The signal operation increments the value of its argument S.

signal(S){
   S++;
}

Updated on: 07-Nov-2023

28K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements