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 achieved it, let me know.
That was easy. But the synchronisation 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.
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, which are meant for a thread safe reading and writing.
It's so easy, but. The confusion starts exactly here. The keyword volatile in Java and C# has the meaning of std::atomic in C++. Or, to say if differently. volatile has no multithreading semantic in the C++.
volatile is typically used in the 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 independent of the regular program flow, there value will directly be written in 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 behaviour and I can not reason about x and y.

CppMem
volatile has no multithreading semantic. 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 assess 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, Animus24, 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, and Dominik Vošček.
Thanks, in particular, to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, John Nebel, Mipko, Alicja Kaminska, and Slavko Radman.
My special thanks to Embarcadero 
My special thanks to PVS-Studio 
My special thanks to Tipi.build 
Seminars
I'm happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.
Bookable (Online)
German
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++
New
- Clean Code with Modern C++
- C++20
Contact Me
- Phone: +49 7472 917441
- Mobil:: +49 176 5506 5086
- Mail: This email address is being protected from spambots. You need JavaScript enabled to view it.
- German Seminar Page: www.ModernesCpp.de
- Mentoring Page: www.ModernesCpp.org
Modernes C++,

Read more...