Getting C++ Threads Right
Why Stack Overflow recommends it
Stack Overflow users link it when explaining C++ memory ordering, compiler and hardware reordering, fences, and why threads and locks need a proper language-level memory model.
Recommended by 2 people across 3 different months, 2009 to 2012.
What it is
A 2007 Google Tech Talk on the industry-wide problems with writing multithreaded code in C and C++ using standard thread libraries, from library and compiler behavior down to hardware reordering. It outlines the proposals being worked into the next C++ standard to give threads a coherent memory model.
What people said
Recommends Johannes Schaub - litb · 2009-05 · Stack Overflow · on “Any Macro or Technic for Part Optimization?”
watched the videos again today and will see how i can change my answer to reflect the new things. Yeah the __sync things are the way to do. Inserting fences at proper place. C++1x will have those too, also having atomic types. watch this vid for more: [this video]
Recommends Johannes Schaub - litb · 2009-10 · Stack Overflow · on “Do sequence points prevent code reordering across critical section boundaries?”
+1. Although mutexes aren't of course specified by C++ so we cannot really formally say what happens here beyond assuming volatileness of both the mutex and the data. In POSIX at least (if i remember correctly), it is allowed that the compiler slurps statements from outside the critical section into the critical section. It however doesn't allow promoting statements from within the critical section outwards (obviously). I like this video: [this video]
Recommends Tim · 2011-02 · Stack Overflow · on “how to make an application thread safe?”
I'm pretty sure this is it: Getting C++ Threads Right [this video] . At 8:20 he gets into some of the hardware reordering of instructions, and mentions write buffers, which can lead to some weird behavior.
Cites nosid · 2012-04 · Stack Overflow · on “Are constructors thread safe in C++ and/or C++11?”
Reasoning about thread-safety can be difficult, and I am no expert on the C++11 memory model. Fortunately, however, your example is very simple. I rewrite the example, because the constructor is irrelevant. Simplified Example Question: Is the following code correct? Or can the execution result in undefined behavior ? // Legal transfer of pointer to int without data race. // The receive function blocks until send is called. void send(int*); int* receive(); // --- thread A --- /* A1 */ int* pointer = receive(); /* A2 */ int answer = *pointer; // --- thread B --- int answer; /* B1 */ answer = 42; /* B2 */ send(&answer); // wait forever Answer: There may be a data race on the memory location of