C++ Core Guidelines: More Rules about 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 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
volatile
for synchronization
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 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.
int get_id() { static int id = 1; return id++; }
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:
unsigned val; if (val < 5) { switch (val) { case 0: // ... case 1: // ... case 2: // ... case 3: // ... case 4: // ... } }
Modernes C++ Mentoring
Do you want to stay informed: Subscribe.
The compiler will often implement the switch block as a jump table. Conceptually, it may look like this.
if (val < 5){ // (1) functions[val](); }
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 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.
const int val = 2011; thread t1([&val]{ .... }; thread t2([&val]{ .... };
- Use constant expressions because they are initialized at compile time.
constexpr auto doub = 5.1;
- 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.
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);
- Use static variables with block scope because the C++11 runtime guarantees that they are initialized 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 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.
// thread int res; thread t([&]{ res = 3 + 4; }); t.join(); cout << res << endl; // task auto fut = async([]{ return 3 + 4; }); cout << fut.get() << endl;
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.
CP.8: Don’t try to use volatile
for synchronization
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.
What’s next?
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, 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, Stephen Kelley, Kyle Dean, Tusar Palauri, 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, Bhavith C Achar, Marco Parri Empoli, Philipp Lenk, Charles-Jianye Chen, Keith Jeffery,and Matt Godbolt.
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 | |
My special thanks to SHAVEDYAKS |
Modernes C++ GmbH
Modernes C++ Mentoring (English)
Rainer Grimm
Yalovastraße 20
72108 Rottenburg
Mail: schulung@ModernesCpp.de
Mentoring: www.ModernesCpp.org
Modernes C++ Mentoring,
Leave a Reply
Want to join the discussion?Feel free to contribute!