Grokking Multithreading and Concurrency for Coding Interviews
Ask Author
Back to course home

0% completed

Vote For New Content
Critical Section and Race Condition
Table of Contents

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible

In concurrent programming, especially with multithreading, there's a critical part of the code known as the Critical Section. This is where threads access shared resources or variables. It's crucial to safeguard this section to prevent conflicts. Why? Because when several threads simultaneously access and modify shared data, it can lead to unpredictable and undesirable outcomes, a phenomenon known as a Race Condition.

A race condition arises when multiple threads concurrently access a shared resource, such as a variable or a file, and at least one of these accesses involves modifying or updating the resource. If the sequence of these accesses impacts the expected outcome, it's flagged as a race condition.

Illustrative Example

Imagine a situation where a shared memory cell holds the value 20. A race condition can occur if four threads read this value at the same time and each attempts to increment it without proper coordination.

Here's What Goes Wrong

  1. All four threads read the value "20" from the memory cell almost at the same moment.
  2. Each thread independently adds one to the value, assuming the memory value is still "20".
  3. Consequently, all threads attempt to write "21" back to the memory cell.

The Ideal Scenario

In a properly synchronized operation, the final value in the memory cell would be "24", with each thread sequentially adding one to the value.

The Solution

To avert such race conditions, it's essential to regulate access to the critical section. This can be achieved through synchronization tools like mutexes or semaphores.

The Synchronized Method

  1. The first thread locks access to the memory cell, then reads the value "20"
  2. It increments the value to "21" and writes it back.
  3. After releasing the lock, the next thread is allowed to access the same memory cell. so it will see an updated value of "21".
  4. This sequence continues, ensuring each thread's increment operation is completed before the next thread accesses the value.
mediaLink

Race Conditions

1 of 8

.....

.....

.....

Like the course? Get enrolled and start learning!

Table of Contents

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible