Ongoing Optimization: Locks and Volatile with CppMem

Contents[Show]

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.

 sukzessiveOptimierungLocksEng

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++.

  1. volatile is for special objects, on which optimized read or write operations are not allowed.
  2. 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.

undefinedEng

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, 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, and Robin Furness.

 

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

 

 

My special thanks to Embarcadero CBUIDER STUDIO FINAL ICONS 1024 Small

 

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.

New

Contact Me

Modernes C++,

RainerGrimmSmall

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

Visitors

Today 744

Yesterday 5860

Week 744

Month 175454

All 7237744

Currently are 143 guests and no members online

Kubik-Rubik Joomla! Extensions

Latest comments