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> std::mutex mu; void ShowMessage(std::string msg) { std::cout << "Thread " << this_thread::get_id() << " says " << msg << std::endl; } int main() { thread t1(ShowMessage, "Hello from Jupiter"); thread t2(ShowMessage, "Hello from Saturn"); thread t3(ShowMessage, "Hello from Mars"); ShowMessage("Hello from Main/Earth"); thread t4(ShowMessage, "Hello from Uranus"); thread t5(ShowMessage, "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 ShowMessage() to acquire a mutex before using std::cout and release it after it is done.
void ShowMessage(std::string msg) { mu.lock(); std::cout << "Thread " << this_thread::get_id() << " says " << msg << std::endl; mu.unlock(); }