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

0% completed

1. Mutex (Lock)
Table of Contents

The following code illustrates the crucial role of a mutex in synchronizing access to a shared resource.

In this demonstration, we use two threads to increment the value of a counter. In one scenario, a mutex is employed to securely read and update the counter's value. In contrast, the second scenario omits the mutex, performing the same operations.

We introduce a sleep function to amplify the issue, creating a deliberate delay between each thread's reading and updating actions.

Observe that the final value of the counter is inaccurate when incremented without a mutex. Ideally, a counter incremented 100 times by 2 threads should result in a total of 200.

Python3
Python3

. . . .
Mark as Completed

Table of Contents