std::shared_mutex


std::shared_mutex are usually used in situations when multiple readers can access the same resource at the same time without causing data races, but only one writer can do so.
To protect shared data from being simultaneously accessed by multiple threads.

#include<iostream>
#include<mutex>
#include<shared_mutex>
#include<thread>

class MutipleReaderSingleWriter
{
          int get() const
          {
                   std::shared_lock<std::shared_mutex> lock(mutex_);
                   return _value;
          }

          void increment()
          {
                   std::unique_lock<std::shared_mutex> lock(mutex_);
                    _value++;
          }
         
          private:
                   mutable std::shared_mutex mutex_;
                   int _value = 0;
};

int main()
{
          MutipleReaderSingleWriter list;
         
          auto incrementAndPrint = [&list](){
                   for(int i=0 ; i<3 ; ++i) {
                             list.increment();
                             cout<<std::this_thread::get_id() << " "<<list.get() <<endl;
                             }
                   }
                  
          std::thread thread1(incrementAndPrint);
          std::thread thread2(incrementAndPrint);
         
          thread1.join();
          thread2.join();
}

The get() function which prints the value is protected with shared_lock, multiple threads can read the data and increment fun which modifies the value is protected with unique_lock, exclusive access.


class shared_mutex // shared_mutex class.

Below lists its member functions


  • void lock() -- Locks the mutex , blocks if the mutex is not available,
  • bool try_lock() -- Tries to lock the mutex. Returns immediately, True if successfull other returns false.
  • void unlock() -- Unlocks the mutex 
  • void lock_shared() -- Acquires shared ownership of the mutex. If another thread is holding the mutex in exclusive ownership, a call to lock_shared will block execution until shared ownership can be acquired.
  • bool try_lock_shared() -- Tries to lock the mutex in shared mode. On success returns True else false.
  • void unlock_shared() -- Releases the mutex from shared ownership by the calling thread.
The class std::shared_lock is a shared mutex ownership wrapper and locks the associated shared mutex in shared mode. use std::unique_lock to lock it in exclusive mode.

Comments

Popular posts from this blog

C++ Guidelines for Multithreaded System

Signalling System #7(SS7) Protocol.

std::shared_ptr