Critical section

[1] Different codes or processes may consist of the same variable or other resources that must be read or written but whose results depend on the order in which the actions occur.

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.

To ensure exclusive use of critical sections, some synchronization mechanism is required at the entry and exit of the program.

This prevents conflicts when two or more threads share the same memory space and want to access a common resource.

[2] The simplest method to prevent any change of processor control inside the critical section is implementing a semaphore.

Semaphore locking also has a time limit to prevent a deadlock condition in which a lock is acquired by a single process for an infinite time, stalling the other processes that need to use the shared resource protected by the critical section.

[4] Once the critical section is exited, and in some cases the scheduled quantum completed, the pending interrupt will be executed.

[5] Most processors provide the required amount of synchronization by interrupting the current execution state.

Critical sections should be kept short enough so they can be entered, executed, and exited without any interrupts occurring from the hardware and the scheduler.

[6] To improve the efficiency of implementing data structures, multiple operations such as insertion, deletion, and search can be executed in parallel.

To prevent this, one method is to keep the entire data structure under critical section so that only one operation is handled at a time.

The concept of critical sections is equally relevant to storage devices as to shared data structures in main memory.

Flow graph depicting need for critical section
Locks and critical sections in multiple threads
Pseudocode for implementing critical section