Lably
Skip to content

Critical section

Protected section of code that cannot be executed by more than one process at a time

  • 7 min read
  • 3 chapters

Related on Lably

Through Shared resource, Data structure and Mutual exclusion

Need for critical sections

Different code 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. For example, if a variable x is to be read by process A, and process B must write to the variable x at the same time, process A might get either the old or new value of x.

Process A:

<span id="mwHg"></span><span class="c1" id="mwHw">// Process A</span> <span class="p" id="mwIA">.</span> <span class="p" id="mwIQ">.</span> <span class="n" id="mwIg">b</span><span class="w" id="mwIw"> </span><span class="o" id="mwJA">=</span><span class="w" id="mwJQ"> </span><span class="n" id="mwJg">x</span><span class="w" id="mwJw"> </span><span class="o" id="mwKA">+</span><span class="w" id="mwKQ"> </span><span class="mi" id="mwKg">5</span><span class="p" id="mwKw">;</span><span class="w" id="mwLA"> </span><span class="c1" id="mwLQ">// instruction executes at time = Tx</span> <span class="p" id="mwLg">.</span>

Process B:

<span id="mwMw"></span><span class="c1" id="mwNA">// Process B</span> <span class="p" id="mwNQ">.</span> <span class="p" id="mwNg">.</span> <span class="n" id="mwNw">x</span><span class="w" id="mwOA"> </span><span class="o" id="mwOQ">=</span><span class="w" id="mwOg"> </span><span class="mi" id="mwOw">3</span><span class="w" id="mwPA"> </span><span class="o" id="mwPQ">+</span><span class="w" id="mwPg"> </span><span class="n" id="mwPw">z</span><span class="p" id="mwQA">;</span><span class="w" id="mwQQ"> </span><span class="c1" id="mwQg">// instruction executes at time = Tx</span> <span class="p" id="mwQw">.</span>

In cases where a locking mechanism with finer granularity is not needed, 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 is 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.

Sign in to keep reading

2 more chapters are free with a Lably account.

More in Computing and communication