The Wayback Machine - https://web.archive.org/web/20240529184244/https://www.geeksforgeeks.org/std-shared_mutex-in-cpp/
Open In App

std::shared_mutex in C++

Last Updated : 25 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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++.

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.
exclusive lock in c++

Exclusive Lock in C++

  • 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.
shared_lock in c++

Shared Lock in C++

Note: Multiple threads can aquire the shared lock simultaneously but only one thread can aquire the exclusive lock at a time.

Methods Associated with std::shared_mutex

The std::shared_mutex contains several member methods that are required to perform different operations. Some of the commonly used functions are:

S. No.  

Function

Description

1

lock() Exclusively locks the mutex and blocks if it fails.

2

unlock() Unlock the exclusive lock.

3

try_lock() Tries to uniquely lock the mutex. This function doesn’t block and returns false if the mutex is already locked for exclusive access.

4

lock_shared() Gets the mutex to use a shared lock.

5

unlock_shared() Unlocks the shared lock for the current thread.

6

try_lock_shared()       Tries for shared lock. This function doesn’t block and returns false if fails.

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 vs std::mutex

Similar to std::mutex, std::shared_mutex is a synchronization primitive that prevents concurrent access to shared resources. Both have their own advantages and disadvantages.

Advantages of std::shared_mutex over std::mutex

The std::shared_mutex has the following advantages over std::mutex:

  • Enhanced Parallelism: Multiple threads can access the shared data for reading operation at once enhancing the parallelism of the program where only read operation is required.

Advantages of std::shared_mutex over std::mutex

  • Limited Flexibility: There are only two types of locks that the std::shared_mutex supports: shared locks and unique locks. Additional lock types, such as recursive and postponed locks, are supported via the std::mutex.
  • Increased Complexity: Compared to std::mutex, std::shared_mutex has greater complexity. It may become more challenging to understand and apply.

Applications

Following are some main applications of std::shared_mutex:

  • When reading data is the primary operation and writing data is uncommon, shared mutexes offer effective parallelism.
  • Shared mutexes can be used in caching algorithms to enable simultaneous updating of the cache by one thread while allowing several threads to read data that has been cached.
  • Database connection pooling allows for simultaneous reading and updating of connection information by several threads, but not for simultaneous modification.

Conclusion

std::shared_mutex is one of the useful mechanisms for access synchronization in multithreaded environments. It works especially effectively in scenarios where the shared data is mostly read-only. But before utilizing the std::shared_mutex, it’s crucial to be aware of its limitations.



Similar Reads

std::fixed, std::scientific, std::hexfloat, std::defaultfloat in C++
Formatting in the standard C++ libraries is done through the use of manipulators, special variables or objects that are placed on the output stream. There are two types of floating point manipulators namely, fixed floating point and scientific floating point. These all are defined in header &lt;iostream&gt;. Use of precision : In the default floati
3 min read
std::oct , std::dec and std::hex in C++
This function is used to set the base to octal, decimal or hexadecimal. It sets the basefield format flag for the str stream to the specified base std::oct : When basefield is set to octal, integer values inserted into the stream are expressed in octal base (i.e., radix 8). For input streams, extracted values are also expected to be expressed in oc
2 min read
std::string::length, std::string::capacity, std::string::size in C++ STL
Prerequisite: String in C++ String class is one of the features provided by the Standard template library to us, So it comes up with great functionality associated with it. With these Functionalities, we can perform many tasks easily. Let's see a few of the functionalities string class provides. Header File &lt;string&gt; String Functionalities The
6 min read
std::stod, std::stof, std::stold in C++
std::stod() : It convert string into double. Syntax: double stod( const std::string&amp; str, std::size_t* pos = 0 ); double stod( const std::wstring&amp; str, std::size_t* pos = 0 ); Return Value: return a value of type double Parameters str : the string to convert pos : address of an integer to store the number of characters processed. This param
3 min read
std::setbase, std::setw , std::setfill in C++
The useful input/output manipulators are std::setbase, std::setw and std::setfill. These are defined in and are quite useful functions. std::base : Set basefield flag; Sets the base-field to one of its possible values: dec, hex or oct according to argument base.Syntax : std::setbase (int base);decimal : if base is 10hexadecimal : if base is 16octal
3 min read
Difference between std::set vs std::vector in C++ STL
Vectors: Vectors are containers similar to dynamic arrays, with the ability to resize when a new element is inserted or deleted from it. It is a template of Standard Template Library or STL, which provides more flexibility to the program. Elements of vectors are placed in contiguous storage and are traversed using iterators. Examples: vector &lt;in
3 min read
std::istream_iterator and std::ostream_iterator in C++ STL
The STL is a very powerful library in C++. It is strongly built on the principles of template programming. The STL library has three main components : Containers: These classes define the data structures which are used to contain the data. The data may be stored in linked lists, or trees or arrays. The containers provided in the STL are vector, deq
6 min read
Difference between std::swap and std::vector::swap
The std::swap is a general function used to exchange the given values whereas the std::vector::swap is a specialized function that can swap all the contents of two different vector containers.Below are some major key differences between std::swap and std::vector::swap, std::swapstd::vector::swapThe std::swap() is a built-in function in C++ STL whic
3 min read
std::bitset::to_ullong and std::bitset::to_ulong in C++ STL
Bitset: A bitset is an array of bool but each Boolean value is not stored separately instead bitset optimizes the space such that each bool takes 1 bit space only, so space taken by bitset bs is less than that of bool bs[N] and vector bs(N). However, a limitation of bitset is, N must be known at compile time, i.e., a constant (this limitation is no
2 min read
std::string::remove_copy(), std::string::remove_copy_if() in C++
remove_copy() It is an STL function in c++ which is defined in algorithm library. It copies the elements in the range [first, last) to the range beginning at result, except those elements that compare equal to given elements. The resulting range is shorter than [first,last) by as many elements as matches in the sequence, which are "removed". The re
4 min read
Practice Tags :