Writing multithreading programs is hard, even harder if the program should be correct. The rules of the C++ Core Guidelines guide you to writing 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.
- CP.2: Avoid data races
- CP.3: Minimize explicit sharing of writable data
- CP.4: Think in terms of tasks, rather than threads
- CP.8: Don’t try to use
Let me directly jump into the first rule.
I already defined the term data race in the last post; therefore, I can make it short. A data race is a concurrent writing and reading of data. The effect is undefined behavior. The C++ Core Guidelines provide a typical example of a data race: a static variable.
What can go wrong? For example, thread A and thread B read the same value, k for id. Afterward, 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:
The compiler will often implement the switch block as a jump table. Conceptually, it may look like this.
In this case, functions() 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.
This is a straightforward to follow but a significant rule. If your share data, it should be constant.
Now, you have only to solve the challenge that the shared data is initialized in a thread-safe way. C++11 supports a few ways to achieve this.
- Initialize your data before you start a thread. This is not due to C++11 but often quite easy to apply.
- Use constant expressions because they are initialized at compile time.
- Use the function std::call_once in combination with the std::once_flag. You can put the critical initialisation stuff into the function onlyOnceFunc. The C++ runtime guarantees that this function runs exactly once successfully.
- Use static variables with block scope because the C++11 runtime guarantees that they are initialized in a thread-safe way.
First of all. What is a task? A task is a term in C++11 that 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, a std::packaged_task, or a std::promise have in common that they are quite low-level; therefore, I will write about a std::async.
Here are a thread and a future and promise pair to calculate the sum of 3 + 4.
What is the fundamental difference between a thread and 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.
If you want an atomic in Java or C# you declare it as volatile. Relatively easy in C++, or? If you want to have an atomic in C++, use volatile. Wrong. volatile has no multithreading-semantic in C++. Atomics is called std::atomic in C++11.
Now, I’m curious: What does volatile mean in C++? volatile is for special objects on which optimized read or write operations are not allowed.
volatile is typically used in 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 be written directly to the main memory. So there is no optimized storing in caches.
Correct multithreading is hard. This is why you should use each possible tool to validate your code. With the dynamic code analyzer ThreadSanitizer and the static code analyzer CppMem two tools 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, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Jozo Leko, John Breland, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Kris Kafka, Mario Luoni, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Daniel Hufschläger, Alessandro Pezzato, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Michael Dunsky, Leo Goodstadt, John Wiederhirn, Yacob Cohen-Arazi, Florian Tischler, Robin Furness, Michael Young, Holger Detering, Bernd Mühlhaus, Matthieu Bolt, Stephen Kelley, Kyle Dean, Tusar Palauri, Dmitry Farberov, Juan Dent, George Liao, Daniel Ceperley, Jon T Hess, Stephen Totten, Wolfgang Fütterer, Matthias Grün, Phillip Diekmann, Ben Atakora, Ann Shatoff, Rob North, and Bhavith C Achar.
Thanks, in particular, to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, John Nebel, Mipko, Alicja Kaminska, Slavko Radman, and David Poole.
|My special thanks to Embarcadero|
|My special thanks to PVS-Studio|
|My special thanks to Tipi.build|
|My special thanks to Take Up Code|
I’m happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.
- Embedded Programmierung mit modernem C++ 12.12.2023 – 14.12.2023 (Präsenzschulung, Termingarantie)
Standard Seminars (English/German)
Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.
- C++ – The Core Language
- C++ – The Standard Library
- C++ – Compact
- C++11 and C++14
- Concurrency with Modern C++
- Design Pattern and Architectural Pattern with C++
- Embedded Programming with Modern C++
- Generic Programming (Templates) with C++
- Clean Code with Modern C++
- Phone: +49 7472 917441
- Mobil:: +49 176 5506 5086
- Mail: schulung@ModernesCpp.de
- German Seminar Page: www.ModernesCpp.de
- Mentoring Page: www.ModernesCpp.org
Modernes C++ Mentoring,