C++ Core Guidelines: More Rules to Concurrency and Parallelism


C++ Core Guidelines: More Rules to Concurrency and Parallelism

Writing multithreading programs is hard, even harder if the program should be correct. The rules of the C++ Core Guidelines guide you to write correct programs. The rules of this post will deal with data races, sharing of data, tasks, and the infamous keyword volatile.

Here are the five rules for more details.

Let me directly jump into the first rule.

CP.2: Avoid data races

I already defined the term data race in thelast post; therefore, I can make it short. A data race is a concurrently writing and reading of data. The effect is undefined behaviour. The C++ Core Guidelines provides a typical example of data race: a static variable.

int get_id() {
  static int id = 1;
  return id++;

What can go wrong? For example, thread A and thread B reads the same value k for id. Afterwards, thread A and thread B writes the value k + 1 back. In the end, the id k + 1 exists twice.

The next example is quite surprising. Here is a small switch block:

unsigned val;

if (val < 5) {
    switch (val) {
    case 0: // ...
    case 1: // ...
    case 2: // ...
    case 3: // ...
    case 4: // ...

The compiler will often implement the switch block as a jump table. Conceptually, it may look like this.

if (val < 5){
    // (1)

In this case, functions[3]() stands for the functionality of the switch block if val is equal to 3. Now it could happen, that another thread kicks in and changes the value at (1) so that it is outside the valid range. Of course, this is undefined behaviour.

CP.3: Minimize explicit sharing of writable data

This is a straightforward to follow but very important rule. If your shared data, it should be constant.

Now, you have only to solve the challenge that the shared data is initialised in a thread-safe way. C++11 support a few ways to achieve this.

  1. Initialise your data before you start a thread. This is not due to C++11 but often quite easy to apply.
    const int val = 2011;
    thread t1([&val]{ .... };
    thread t2([&val]{ .... };
  2. Use constant expression because they are initialised at compile time.
    constexpr auto doub = 5.1;
  3. Use the function std::call_once in combination with the std::once_flag. You can put the important initialisation stuff into the function onlyOnceFunc . The C++ runtime guarantees that this function runs exactly once successfully.
    std::once_flag onceFlag;
    void do_once(){
      std::call_once(onceFlag, [](){ std::cout << "Important initialisation" << std::endl; });
    std::thread t1(do_once);
    std::thread t2(do_once);
    std::thread t3(do_once);
    std::thread t4(do_once);
  4. Use static variables with block scope because the C++11 runtime guarantees that they are initialised in a thread-safe way.
    void func(){
      static int val 2011; 
    thread t5{ func() };
    thread t6{ func() };

First of all. What is a task? A task is a term in C++11 which stands for two components: a promise and a future. Promise exists in three variations in C++: std::async, std::packaged_task, and std::promise. I have already written a few posts ontasks.

A thread, an std::packaged_task, or an std::promise have in common that they are quite low-level; therefore, I will write about an std::async .

Here are a thread and a future and promise pair to calculate the sum of 3 + 4.

// thread
int res;
thread t([&]{ res = 3 + 4; });
cout << res << endl;

// task
auto fut = async([]{ return 3 + 4; });
cout << fut.get() << endl;

What is the fundamental difference between a thread an a future and promise pair? A thread is about how something should be calculated; a task is about what should be calculated.

Let me be more specific.

  • The thread uses the shared variable res to provide its results. In contrast, the promise std::async uses a secure data channel to communicate its result to the future fut.T his means for the thread in particular that you have to protect res.
  • In case of a thread, you explicitly create a thread. This will not hold for the promise because you just specify what should be calculated.

CP.8: Don’t try to use volatile for synchronization

If you want to have an atomic in Java or C# you declare it as volatile . Quite easy in C++, or? If you want to have an atomic in C++, use volatile . Totally wrong. volatile has no multithreading-semantic in C++. Atomics are called std::atomic in C++11.

Now, I’m curious: What is the meaning of volatile in C++? volatile is for special objects, on which optimized read or write operations are not allowed.

volatile is typically used in the embedded programming to denote objects, which can change independently of the regular program flow. These are for example objects, which represent an external device (memory-mapped I/O). Because these objects can change independently of the regular program their value will directly be written to main memory. So there is no optimised storing in caches.

What’s next?

Correct multithreading is hard. This is the reason you should use each possible tool to validate your code. With the dynamic code analyser ThreadSanitizer and the static code analyser CppMem there are two tools which should be in the toolbox of each serious multithreading programmer. In the next post, you will see why.

Thanks a lot to my
Patreon Supporters

: Eric Pederson, Paul Baxter, Sai Raghavendra Prasad Poosa, Meeting C++, Matt Braun, Avi Lachmish, and Adrian Muntea.

Get your e-book at leanpub:

The C++ Standard Library

Concurrency With Modern C++

Get Both as one Bundle

With C++11, C++14, and C++17 we got a lot of new C++ libraries. In addition, the existing ones are greatly improved. The key idea of my book is to give you the necessary information to the current C++ libraries in about 200 pages.

C++11is the first C++ standard that deals with concurrency. The story goes on with C++17 and will continue with C++20 .

I’ll give you a detailed insight in the current and the upcoming concurrency in C++. This insight includes the theory and a lot of practice with more the 100 source files.

Get my books ” The C++ Standard Library ” (including C++17) and ” Concurrency with Modern C++ ” in a bundle.

In sum, you get more than 550 pages full of modern C++ and more than 100 source files presenting concurrency in practice.


C++ Core Guidelines: More Rules to Concurrency and Parallelism

20 Coolest Cinema 4D Templates


How GDPR Impacts Marketers: What You Need to Know



C++ Core Guidelines: More Rules to Concurrency and Parallelism