January 2020
Intermediate to advanced
454 pages
11h 25m
English
In this recipe, we will learn how to create thread-safe synchronization wrappers, which allow us to add thread-safety to the C++ standard library data structures, which, by default, are not thread-safe.
To do this, we will create wrapper functions for each function in the C++ standard library that we intend to use. These wrapper functions will first attempt to acquire std::mutex, before forwarding the same function call to the C++ standard library data structure.
To do this, consider the following code example:
#include <mutex>#include <stack>#include <iostream>std::mutex m{};template<typename S, typename T>void push(S &s, T &&t){ std::lock_guard lock(m); s.push(std::forward<T>(t));}template<typename S>void pop(S &s){ std::lock_guard ...