Grokking Multithreading and Concurrency for Coding Interviews
Vote

0% completed

1. Mutex (Lock)

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

. . . .
Shouvik Pradhan

Shouvik Pradhan

· a year ago

The primary use of the join() method is to pause the current thread (the thread that calls join()) until another thread (the thread specified as the argument to join()) terminates