C++ Core Guidelines: The Remaining Rules about Lock-Free Programming

Contents[Show]

Today, I will finish my story on concurrency and lock-free programming in particular. There are four rules to lock-free programming in the C++ core guidelines left.

First of all, here are the rules for the current post.

I have to admit, I annoyed a few German readers with my two last posts about lock-free programming. My readers got the impression, that I don't like lock-free programming. Wrong!. I'm totally curious about lock-free programming but before you use it you have to answer two questions.

1. Does lock-free programming solve my performance bottleneck?
2. Do I understand lock-free programming good enough to use it?

Before you can not answer these two questions with a big yes, you should continue with the rule CP.102

What does that mean: distrust your hardware/compiler combination. Let me put it in another way: When you break the sequential consistency, you will also break with high probability your intuition. Here is my example:

```#include <atomic>
#include <iostream>

std::atomic<int> x{0};
std::atomic<int> y{0};

void writing(){
x.store(2000);                        // (1)
y.store(11);                          // (2)
}

std::cout << y.load() << " ";         // (3)
std::cout << x.load() << std::endl;   // (4)
}

int main(){
}
```

I have a question for the short example? Which values für y and x are possible in the lines (3) and (4). x and y are atomic, therefore no data race is possible. I further don't specify the memory ordering, therefore, sequential consistency applies. Sequential consistency means:

• Each thread performs its operation in the specified sequence: line (1) happens before line (2) and line (3) happens before line(4).
• There is a global order of all operations on all threads.

If you combine these two properties of the sequential consistency, there is only one combination of x and y not possible: y == 11 and x == 0.

Now, let me break the sequential consistency and maybe your intuition. Here is the weakest of all memory orderings: the relaxed semantics.

```#include <atomic>
#include <iostream>

std::atomic<int> x{0};
std::atomic<int> y{0};

void writing(){
x.store(2000, std::memory_order_relaxed);   // (1)
y.store(11, std::memory_order_relaxed);     // (2)
}

std::cout << y.load(std::memory_order_relaxed) << " ";        // (3)
std::cout << x.load(std::memory_order_relaxed) << std::endl;  // (4)
}

int main(){
}
```

Two unintuitive phenomena can happen. First, thread2 can see the operations of thread1 in a different sequence. Second, thread1 can reorder its instruction because they are not performed on the same atomic.  What does that mean for the possible values of x and y: y == 11 and x == 0 is a valid result. I want to be a little bit more specific. Which result is possible depends on your hardware.

For example, operation recording is quite conservative on x86 or AMD64, stores can be reordered after loads but on Alpha, IA64, or RISC (ARM) architectures, all four possible reorderings of stores and loads operations are allowed.

If you don't believe me, I suggest you read the following rule CP.102.

Modernes C++ Mentoring

Stay informed about my mentoring programs. Subscribe for the news.

CP.102: Carefully study the literature

There is not much to add to this rule. At least, I can provide links to the literature.

CP.110: Do not write your own double-checked locking for initialization andCP.111: Use a conventional pattern if you really need double-checked locking

I know, I should not write about the singleton pattern but the double-checked locking pattern is infamous for initialising a singleton in a thread-safe way. Here we are:

```std::mutex myMutex;

class MySingleton{
public:
static MySingleton& getInstance(){
std::lock_guard<std::mutex> myLock(myMutex);       // (1)
if( !instance ) instance= new MySingleton();
return *instance;
}
private:
MySingleton();
~MySingleton();
MySingleton(const MySingleton&)= delete;
MySingleton& operator=(const MySingleton&)= delete;
static MySingleton* instance;
};
MySingleton::MySingleton()= default;
MySingleton::~MySingleton()= default;
MySingleton* MySingleton::instance= nullptr;
```

This implementation of the singleton pattern is thread-safe because each access to the instance is protected by a std::lock_guard (line (1)). The implementation is correct but way to expensive because each reading access of the singleton is guarded by a heavy-weight lock. Besides the initialisation of the singleton, no synchronisation is necessary. Here comes the double-checked locking pattern to our rescue.

```static MySingleton& getInstance(){
if ( !instance ){                              // (1)
lock_guard<mutex> myLock(myMutex);           // (2)
if( !instance ) instance= new MySingleton(); // (3)
}
return *instance;
}
```

The getInstance method uses now an inexpensive pointer comparison in line (1) instead of an expensive lock. Only if the pointer is a nullptr, an expensive lock is used (line (2)). Because there is the possibility that another thread will initialise the singleton between the pointer comparison (line (1)) and the lock (line (2)), an additional pointer comparison in line (3) is necessary. So the name is obvious. Two times a check and one time a lock.

What is the problem? The call instance= new MySingleton() inline (3) consists of at least three steps.

1. Allocate memory for MySingleton
2. Create the MySingleton object in the memory
3. Let instance refer to the MySingleton object

The problem is that there is no guarantee about the sequence of these three steps. For example, the processor can reorder the steps to the sequence 1,3 and 2. So, in the first step, the memory will be allocated and in the second step, the instance refers to the singleton. If at that time another thread tries to access the singleton, it compares the pointer and assumes that the singleton is fully initialised.

The consequence is simple: the program has undefined behaviour.

I have already written a quite emotionally discussed post to the thread-safe singleton pattern. This included different implementations with std::lock_guard, std::call_once and std::once_flag, the Meyers singleton, and atomic versions that are based on the double-checked locking-pattern. You can read the details of these implementations and their different performance characteristics on Linux and Windows here:  Thread-Safe Initialization of a Singleton.

What's next?

As I promised I'm done with the rules to concurrency. The next post is about the rules for error handling in the C++ core guidelines.

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, 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, Daniel Hufschläger, Alessandro Pezzato, Evangelos Denaxas, 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, and Wolfgang Fütterer.

Thanks in particular to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, Ralf Abramowitsch, John Nebel, Mipko, Alicja Kaminska, and Matthias Grün.

My special thanks to PVS-Studio

Seminars

I'm happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.

Standard Seminars (English/German)

Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.

Modernes C++,

Tags: lock-free

0 #1 David 2019-09-12 04:09
But out of curiousity, what is the fix.
Just use an atomic operation to load and store the pointer?
0 #2 Rainer 2019-09-19 20:52
0 #3 Stefan 2021-01-20 02:09
std::atomic is not guaranteed to be lock-free. So what's the advice to get lock-free thread synchronization?

Subscribe to the newsletter (+ pdf bundle)

 Email Please enable the javascript to submit this form

Visitors

Today 2910

Yesterday 4105

Week 33928

Month 163433

All 10708549

Currently are 147 guests and no members online

• C++ Core Guidelines: A Short Detour to Contracts in C++20

It would be nice if you put up a disclaimer that contracts did not make it into c++ 20, and this ...

• No New New: Raw Pointers Removed from C++

APRIL FOOLS PRANKs have a ONE DAY LIFESPAN. When left up beyond that they are simply disinformation ...

• No New New: Raw Pointers Removed from C++

This is an APRIL FOOLS PRANK

• The Bridge Pattern

There is a small typo in the article: Bridget Pattern :-)

• The Bridge Pattern

Thank you for this nice description. The implementation of move semantics can be simplified and inlined ...