Mutex

asheesh kumar singhal
1 min readDec 17, 2021

In certain situations we like to perform operations on the same data by multiple threads. However if multiple threads will operate on same data then this could lead to uncertain and ambiguous results. The both of threads will try to get the acquire the data first and this will lead to race condition in which the data will get updated by another thread while the first thread is trying to add the data.

To avoid race condition and ambiguous results we use a method called Mutex. In mutex we will lock the data and another thread will not be to access the it. Mutexes allow us to lock the data and other thread cannot access and modify it.

#include mutex

std::mutex mutex_list

thread 1:

{

mutex_list.lock ()

///here you perform operation the data

mutex.unlock()

}

thread 2:

{

mutex_list.lock ()

///here you perform operation the data

mutex.unlock()

}

This will allow synchronized access to the data. So now only one of them will be able to access the data. Tomake the data accessible to another thread we need to unlock it. if a thread fails to unlock the data, then another thread won’t be able to access it and will go into state of deadlock. thus we need to unlock the data.

However in certain situtation we might return from the function before unlocking it and this can cause deadlock. Hence Its always better to use lock_gaurd. It will automatically lock the mutex and its destructor will automatically unlock it.

--

--