Skip to Content
C++ High Performance
book

C++ High Performance

by Viktor Sehr, Björn Andrist
January 2018
Intermediate to advanced
374 pages
9h 53m
English
Packt Publishing
Content preview from C++ High Performance

Protecting critical sections

As already mentioned, our code must not contain any data races. Unfortunately, writing code with data races is very easy. Finding the critical sections and protecting them with locks is something we constantly need to think about when writing concurrent programs in this style using threads.

C++ provides us with a std::mutex class that can be used for protecting critical sections and avoiding data races. We will demonstrate how to use a mutex with a classic example using a shared mutable counter variable updated by multiple threads.

First, we define a global mutable variable and the function incrementing the counter:

auto counter = 0; // Warning! Global mutable variable auto increment_counter(int n) { for (int ...
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

C++ High Performance - Second Edition

C++ High Performance - Second Edition

Björn Andrist, Viktor Sehr
Advanced C++

Advanced C++

Gazihan Alankus, Olena Lizina, Rakesh Mane, Vivek Nagarajan, Brian Price
C++ In a Nutshell

C++ In a Nutshell

Ray Lischner
C++ Cookbook

C++ Cookbook

D. Ryan Stephens, Christopher Diggins, Jonathan Turkanis, Jeff Cogswell

Publisher Resources

ISBN: 9781787120952Supplemental Content