Mutex Implementation.

Gaurang Patel
4 min readOct 30, 2018

What is a Mutex?

The mutex (In fact, the term mutex is short for mutual exclusion) also known as spinlock is the simplest synchronization tool that is used to protect critical regions and thus prevent race conditions. That is a thread must acquire a lock before entering into a critical section (In critical section multi threads share a common variable, updating a table, writing a file and so on), it releases the lock when it leaves critical section.

Enough of these written explanations. Lets see an example where we can find a need to implement Mutex.

Here in this example we are trying to print even and odd numbers upto the range of 10. For that we are using two threads, one to print even numbers and the other to print odd numbers respectively. We have two functions written here one for even and one for odd. The respective functions are given as ( target=’ ’) to each thread. The argument which is supposed to be passed to the functions is given as args = ‘argument_to_be_passed’.

As we run these lines of code, the output is.

0 is Even
2 is Even
1 is Odd
4 is Even
3 is Odd
6 is Even
5 is Odd
8 is Even
7 is Odd
9 is Odd

--

--

Gaurang Patel

Engineering @ Razorpay! Enabling smoother card payments for 25% Indian everyday.