Ongoing Optimization: Locks and Volatile with CppMem
The easiest way to solve the undefined behaviour in the post Ongoing Optimization: Unsynchronized access is, to use a lock.
Locks
Both threads thread1 and thread2 use the same mutex, wrapped in a std::lock_guard.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
// ongoingOptimizationLock.cpp #include <iostream> #include <mutex> #include <thread> int x= 0; int y= 0; std::mutex mut; void writing(){ std::lock_guard<std::mutex> guard(mut); x= 2000; y= 11; } void reading(){ std::lock_guard<std::mutex> guard(mut); std::cout << "y: " << y << " "; std::cout << "x: " << x << std::endl; } int main(){ std::thread thread1(writing); std::thread thread2(reading); thread1.join(); thread2.join(); }; |
Now, the program is well defined. Either thread1 or thread2 is running. Dependent on that, either both values are or aren’t set. So the following values for x and y are possible.
CppMem
I didn’t achieve it to use std::lock_guard in CppMem. Sorry. But if you achieve it, let me know.
That was easy. But the synchronization with locks is too heavyweight. The freedom of the system to optimize the program is drastically reduced. There are only two possibilities. So, what should I do next? Of course, switch to atomics.
There is the volatile keyword in C++. Let’s try it out.
Modernes C++ Mentoring
Do you want to stay informed: Subscribe.
volatile
What has the keyword volatile in C# and Java with the keyword volatile in C++ in common? Nothing!
It’s so easy in C++.
- volatile is for special objects on which optimized read or write operations are not allowed.
- std::atomic defines atomic variables meant for thread-safe reading and writing.
It’s so easy, but. The confusion starts exactly here. The keyword volatile in Java and C# means std::atomic in C++. Or, to say if differently. volatile has no multithreading semantics in C++.
volatile is typically used in embedded programming to denote objects, which can change independent 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 flow, their value will directly be written in the main memory. So there is no optimized storing in caches.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
// ongoingOptimizationVolatile.cpp #include <iostream> #include <thread> volatile int x= 0; volatile int y= 0; void writing(){ x= 2000; y= 11; } void reading(){ std::cout << "y: " << y << " "; std::cout << "x: " << x << std::endl; } int main(){ std::thread thread1(writing); std::thread thread2(reading); thread1.join(); thread2.join(); }; |
So what does that mean for our small program from Ongoing Optimization if I declare the int variables as volatile? I guess you know it. The program has a data race on the variables x and y. So the program has undefined behavior and I can not reason about x and y.
CppMem
volatile has no multithreading semantics. This shows CppMem unambiguously.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
int main(){ volatile int x= 0; volatile int y= 0; {{{ { x= 2000; y= 11; } ||| { y; x; } }}} } |
The results are identical to the results of my analysis in the unsynchronized assessment with non-atomics. So you can read it here in my last post Ongoing Optimization: Unsynchronized access with CppMem. It makes no difference if you use the variables x and y with or without the volatile qualifier.
What’s next?
In the next post, I will make it right. I use atomics with sequential consistency.
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, Matt Godbolt, and Honey Sukesan.
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!