DCLP fixing with volatile only

I am reading the article " C ++ and the Dangers of Double Checked Locking " which explains the problems in DCLP.

The second part of the article (where the redirect link is) shows how to try and solve the DCLP with C / C ++ volatile alone (which from what I know is not possible). In the article, the authors explain how to do this (the last example is number 11), but they write:

Unfortunately, none of this does anything to solve the first problem - the C ++ abstract machine is single-threaded, and C ++ compilers may choose to generate unsafe code from source like that mentioned anyway. Otherwise, lost optimization opportunities lead to too much efficiency. After all this, we will return to the square. But wait, there are more, more processors.

Which means (if I understand correctly) that no matter how well we use volatile, it won't work because "the abstract C ++ machine is single-threaded and C ++ compilers can generate unsafe code from source as mentioned."

But what does it mean: "C ++ abstract machine is single-threaded" ?!

Why won't the above examples with all these volatiles prevent reordering?

Thank!

+3


source to share


2 answers


Since C ++ 11, your bold highlighted proposal is no longer true.

What this has meant in the past:
OS / device can support multiple threads, including functions to run them, etc.

C ++ compilers on the other hand, etc. Think of single-thread environments and are unaware of the potential issues with multiple threads. The initial thread is nothing more than a normal function call for them, and that the OS is doing something weird to the process because the call is not known or interesting.



Reordering code in single-thread environments is possible as long as the reordered parts of the code do not depend on each other (for example, the order of writing or reading a variable in / makes the code using this variable). In a multi-threaded environment, the compiler cannot know if a variable is also affected by another thread ...

Now, in C ++ 11 / C ++ 14, there is OS independent support
to prevent threading code splitting optimization.

+2


source


This means that writes done by a single thread are always displayed directly to themselves and will have the same logical result as if the code were not reordered by the compiler or the CPU, even if it might have happened.

What was broken is how these entries came to be for other threads that share the same data space. This was fixed in C ++ 11.



It also gave a slightly different meaning to const and mutable. The creation of a mutable member is no longer the clutter it ever was, it is now used when the member can be modified by thread-safe, meaning that any changes are visible to other threads in a logical sequential manner. For example. It's fine to make std :: mutex or std :: atomic mutable, but not a simple int.

0


source







All Articles