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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.