January 2020
Intermediate to advanced
454 pages
11h 25m
English
In this recipe, we will learn how to add std::mutex to a class's private members while still being able to handle const scenarios. Generally speaking, there are two ways to ensure an object is thread-safe. The first method is to place std::mutex at the global level. Doing this ensures an object can be passed as a constant reference or the object itself can have a function marked as const.
For this, consider the following code example:
#include <mutex>#include <thread>#include <iostream>std::mutex m{};class the_answer{public: void print() const { std::lock_guard lock(m); std::cout << "The answer is: 42\n"; }};int main(void){ the_answer is; is.print(); return 0;}
In the preceding example, we create an object that outputs to ...