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

0% completed

Vote For New Content
2. Read/Write Locks
Table of Contents

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible

In this demonstration, we interact with a shared variable, counter, that is accessed concurrently by multiple threads. Specifically, we spawn 2 writer threads that increment the counter in a loop and 8 reader threads that continuously read its value. The program is designed to terminate once the counter reaches the TARGET_VALUE.

Key principles to note in this scenario include:

  • Multiple threads can simultaneously read the value of the counter without blocking each other.
  • A writer thread is restricted from updating the counter's value if either another writer is already performing an update, or if any readers are currently accessing the value.
  • Similarly, a reader thread is prevented from accessing the counter if a writer thread is updating its value.

This example showcases the utility of a Reader-Writer lock, which allows multiple threads to read the counter concurrently without significant blocking. This concurrent read capability ensures better performance compared to a scenario where a standard mutex might be used, leading to slower execution due to more restrictive access control.

Python3
Python3

. . . .

Experiment Idea: How about modifying readValue() to use a write-lock for incrementing the counter? Observe the changes in performance, especially in terms of the Time taken. Will this alteration speed up the process or slow it down? Experiment and discover the impact!

.....

.....

.....

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