shared_mutex

shared_mutexes differ from regular mutexes in that they allow two locking modes as follows:

shared_mutexes are often used where multiple readers and single writers require synchronized access to a resource. In this case, readers have shared access (multiple readers can read the resource at once) but only one writer can have exclusive access (and all readers must wait for it).

#include <iostream>
#include <syncstream>

#include <shared_mutex>
#include <thread>
#include <vector>

::std::shared_mutex
   mutex;

::std::string
   content = "Initial Content";

void reader(unsigned thread_index)
{
   mutex.lock_shared();
   
   ::std::osyncstream(::std::cout) << "Thread "
                                   << thread_index
                                   << " read: \""
                                   << content
                                   << "\""
                                   << ::std::endl
                                      ;
   
   mutex.unlock_shared();
   
   return;
}

void modify_content(void)
{
   mutex.lock();
   
   content = "Modified Content";
   
   ::std::osyncstream(::std::cout) << "Writer modified "
                                      "content"
                                   << ::std::endl
                                      ;
   
   mutex.unlock();
   
   return;
}

int main(int argc, char ** argv)
{
   //
   // Create 10 reader threads and one writer thread:
   //
   
   ::std::vector
      <
      ::std::jthread
      >
      readers;
   
   unsigned const
      number_of_threads = 10u;
   
   for(unsigned i(0u); i< number_of_threads; ++i)
   {
      readers.push_back
         (
         ::std::jthread( reader, i )
         )
         ;
   }
   
   ::std::jthread
      writer(modify_content);
   
   return 0;
}
Possible output:
Thread 0 read: "Initial Content" Thread 3 read: "Initial Content" Thread 2 read: "Initial Content" Thread 5 read: "Initial Content" Thread 4 read: "Initial Content" Thread 6 read: "Initial Content" Thread 1 read: "Initial Content" Thread 7 read: "Initial Content" Thread 8 read: "Initial Content" Writer modified content Thread 9 read: "Modified Content"