How to do it...

We are going to write a program that uses an std::shared_mutex instance in its exclusive and shared modes and to see what that means. Additionally, we do not call the lock and unlock functions ourselves but do the locking with automatic unlocking using RAII helpers:

  1. First, we need to include all necessary headers. Because we use STL functions and data structures all the time together with time literals, we declare that we use the std and chrono_literal namespaces:
      #include <iostream>      #include <shared_mutex>      #include <thread>      #include <vector>            using namespace std;      using namespace chrono_literals;
  1. The whole program revolves around one shared mutex, so let's define a global instance for the sake of simplicity:
 shared_mutex ...

Get C++17 STL Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.