In concurrent programming, concurrent accesses to shared resources can lead to unexpected or erroneous behavior, so parts of the program where the shared resource is accessed is protected. This protected section is the critical section or critical region. It cannot be executed by more than one process. Typically, the critical section accesses a shared resource, such as a data structure, a peripheral device, or a network connection, that would not operate correctly in the context of multiple concurrent accesses.
Different codes/processes may consist of the same variables which need to be read or written but which are conflicting in nature. For e.g., a variable ‘x’ is to be read by process A and process B has to write to the same variable ‘x’ at the same time.
Process A:
Process B:
In cases like these, a critical section is important. In the above case, if A needs to read the updated value of ‘x’, executing Process A and Process B at the same time may not give required results. To prevent this, variable ‘x’ is protected by a critical section. First, B gets the access to the section. Once B finishes writing the value, A gets the access to the critical section and variable ‘x’ can be read.
By carefully controlling which variables are modified inside and outside the critical section, concurrent access to the shared variable are prevented. A critical section is typically used when a multi-threaded program must update multiple related variables without a separate thread making conflicting changes to that data. In a related situation, a critical section may be used to ensure that a shared resource, for example, a printer, can only be accessed by one process at a time.
The implementation of critical sections vary among different operating systems.
A critical section will usually terminate in finite time, and a thread, task, or process will have to wait for a fixed time to enter it (bounded waiting). To ensure exclusive use of critical sections some synchronization mechanism is required at the entry and exit of the program.
Critical section is a piece of a program that requires mutual exclusion of access.
As shown in Fig 2, in the case of mutual exclusion (Mutex), one thread blocks a critical section by using locking techniques when it needs to access the shared resource and other threads have to wait to get their turn to enter into the section. This prevents conflicts when two or more threads share the same memory space and want to access a common resource.