Skip to Content
Advanced C++ Programming Cookbook
book

Advanced C++ Programming Cookbook

by Dr. Rian Quinn
January 2020
Intermediate to advanced
454 pages
11h 25m
English
Packt Publishing
Content preview from Advanced C++ Programming Cookbook

How it works...

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Modern C++ Programming Cookbook

Modern C++ Programming Cookbook

Marius Bancila

Publisher Resources

ISBN: 9781838559915Supplemental Content