Data race and mutex
Data race conditions are very common in multithreaded applications, but we must avoid such a scenario so that deadlocks do not happen. A mutex helps us to overcome deadlocks. A mutex is a program object that allows multiple program threads to share the same resource, such as file access, but not simultaneously. When a program is started, a mutex is created with a unique name.
Getting ready
For this recipe, you will need a Windows machine and an installed version of Visual Studio.
How to do it…
In this recipe, we will see how easy it is to understand data races and mutexes. Add a source file called Source.cpp
and add the following code to it:
#include <thread> #include <string> #include <mutex> #include <iostream> using namespace std; std::mutex MU; void Locomotion(string msg, int id) { std::lock_guard<std::mutex> guard(MU); //RAII //MU.lock(); cout << msg << id << endl; //MU.unlock(); } void InterfaceFunction() { ...