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.

thread 841607 640

 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 the last 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 expressions 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() };

CP.4: Think in terms of tasks, rather than threads

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

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.This means for the thread in particular that you have to protect res.
  • In the 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 the 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 that 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: Matt Braun, Roman Postanciuc, Tobias Zindl, Marko, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Animus24, Jozo Leko, John Breland, espkk, Louis St-Amour, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Kris Kafka, Mario Luoni, Neil Wang, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Tobi Heideman, Daniel Hufschläger, Red Trip, Alexander Schwarz, Tornike Porchxidze, Alessandro Pezzato, Evangelos Denaxas, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Michael Dunsky, Dimitrov Tsvetomir, Leo Goodstadt, Eduardo Velasquez, John Wiederhirn, Yacob Cohen-Arazi, Florian Tischler, Robin Furness, and Michael Young.


Thanks in particular to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, and Rusty Fleming.



My special thanks to Embarcadero CBUIDER STUDIO FINAL ICONS 1024 Small



I'm happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.

Bookable (Online)


Standard Seminars (English/German)

Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.


Contact Me

Modernes C++,


My Newest E-Books

Course: Modern C++ Concurrency in Practice

Course: C++ Standard Library including C++14 & C++17

Course: Embedded Programming with Modern C++

Course: Generic Programming (Templates)

Course: C++ Fundamentals for Professionals

Interactive Course: The All-in-One Guide to C++20

Subscribe to the newsletter (+ pdf bundle)

Blog archive

Source Code


Today 4945

Yesterday 8162

Week 21815

Month 140017

All 7407857

Currently are 192 guests and no members online

Kubik-Rubik Joomla! Extensions

Latest comments