Example of std::shared_lock
C++
// C++ program to illustrate the use of shared_mutex #include <iostream> #include <shared_mutex> #include <mutex> #include <thread> using namespace std; // creating a shared_mutex object shared_mutex mutx; int shared_data = 11; // callable with shared lock void readData() { shared_lock<shared_mutex> lock(mutx); cout << "Thread " << this_thread::get_id() << ": " ; cout << shared_data << endl; } // callable with unique_lock void writeData( int n) { unique_lock<shared_mutex> lock(mutx); shared_data = n; cout << "Thread" << this_thread::get_id() << ": \n" ; } // driver code int main() { thread t1(readData); thread t2(writeData, 128); thread t3(writeData, 10); thread t4 (readData); t1.join(); t2.join(); t3.join(); t4.join(); return 0; } |
Output
Read Thread 140122977658432: 11 Write Thread 140122960873024 Write Thread 140122969265728 Read Thread 140122952480320: 128
std::shared_mutex in C++
In C++, std::mutex is a mechanism that locks access to the shared resource when some other thread is working on it so that errors such as race conditions can be avoided and threads can be synchronized. But in some cases, several threads need to read the data from shared resources at the same time. Here, the std::shared_mutex comes into play. In this article, we will discuss the std::shared_mutex, its associated methods, and how it is different from the std::mutex in C++.
Prerequisite: C++ Multithreading, std::mutex in C++.
Contact Us