User Tools

Site Tools


c:c_threads:protected_access_to_shared_data_or_shared_resources:mutex:basic_example

C - C++ Threads - Protected access to shared data or shared resources - Mutex - Basic 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/basic_example.txt · Last modified: 2021/06/08 09:27 by peter

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki