c:c_threads:protected_access_to_shared_data_or_shared_resources:mutex
This is an old revision of the document!
Table of Contents
C - C++ Threads - Protected access to shared data or shared resources - Mutex
The classical way to protect access to a variable is using a mutex.
NOTE: This is known to have much overhead.
Protect shared data or shared resources with a mutex
Example
In this example, 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 " << std::this_thread::get_id() << " says " << msg << std::endl; } int main() { std::thread t1(ShowMessage, "Hello from Jupiter"); std::thread t2(ShowMessage, "Hello from Saturn"); std::thread t3(ShowMessage, "Hello from Mars"); ShowMessage("Hello from Main/Earth"); std::thread t4(ShowMessage, "Hello from Uranus"); std::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 " << std::this_thread::get_id() << " says " << msg << std::endl; mu.unlock(); }
c/c_threads/protected_access_to_shared_data_or_shared_resources/mutex.1623143387.txt.gz · Last modified: 2021/06/08 09:09 by peter