This is an old revision of the document!
C - C++ Threads - Protect shared data or shared resources with a mutex
In a multithreaded environment, more than one thread is often competing for a resource or shared data. This often results in undefined behavior for the resource or data , unless the resource or data is protected using some mechanics that only allows ONE thread to act on it at a time.
In the example below, std::cout is a shared resource that is shared by 6 threads (t1-t5 + main).
#include <iostream> #include <string> #include <thread> #include <mutex> using namespace std; std::mutex mu; void CallHome(string message) { cout << "Thread " << this_thread::get_id() << " says " << message << endl; } int main() { thread t1(CallHome, "Hello from Jupiter"); thread t2(CallHome, "Hello from Pluto"); thread t3(CallHome, "Hello from Moon"); CallHome("Hello from Main/Earth"); thread t4(CallHome, "Hello from Uranus"); thread t5(CallHome, "Hello from Neptune"); t1.join(); t2.join(); t3.join(); t4.join(); t5.join(); return 0; }
NOTE: The output will not be in any specific order.
This is because the five threads get the std::cout resource in a random fashion.
Solution
To make the output more deterministic, the solution is to protect the access to std::cout resource using a std::mutex.
Just change the CallHome() to acquire a mutex before using std::cout and release it after it is done.
void CallHome(string message) { mu.lock(); cout << "Thread " << this_thread::get_id() << " says " << message << endl; mu.unlock(); }