Advanced Concepts in Concurrent Programming

Learn about protecting critical sections, avoiding deadlocks, and using condition variables in advanced concurrent programming.

Protecting critical sections

As we 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:

Get hands-on with 1400+ tech skills courses.