std::shared_mutex in C++
In C++, std::shared_mutex is a synchronization primitive that lets several threads use a shared resource simultaneously for reading while guaranteeing exclusive writing access. It is helpful in situations where many threads need read-only access to the same data structure, but write operations aren’t often used.
Types of Locks in std::shared_mutex
The std::shared_mutex provides two types of locks:
- Unique Lock: It is a unique lock that can only be acquired by a single thread at a time. This lock only allows a single thread to modify the shared resources while blocking the other threads. It is similar to the lock provided by the std::mutex.
- Shared Lock: The shared lock is a non-exclusive lock that several threads can acquire at once. This gives multiple threads read-only access to the shared resource.
Note: Multiple threads can aquire the shared lock simultaneously but only one thread can aquire the exclusive lock at a time.
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