[cpp-threads] [Javamemorymodel-discussion] there's a happens-before orderhere. right?
Anthony Williams
anthony at justsoftwaresolutions.co.uk
Mon Dec 15 11:47:45 GMT 2008
At Sat 13 Dec 2008 14:42:43 UTC, Alexander Terekhov
<alexander.terekhov at gmail.com> wrote:
> Let's take your first example and slightly change it by renaming y
> to "data" and using std::atomic<> for x:
>
> int data; //= 0
> atomic<int> x; //= 0
>
> thread 1:
> ------------
> if (x.load(relaxed) > 0)
> data = 1;
>
> thread 2:
> ------------
> data = 2;
>
> This is still data-race-free, right? I hope so.
There's no writes to x, so the load must always read 0 => no race.
> Now let's introduce a store to std::atomic<> x in thread 2.
>
> int data; //= 0
> atomic<int> x; //= 0
>
> thread 1:
> ------------
> if (x.load(relaxed) > 0)
> data = 1;
>
> thread 2:
> ------------
> data = 2;
> x.store(-1, release);
>
> I just can't conceive how that could possibly introduce a race on
> "data"...
Agreed. The load may read 0 (initial value) or -1 (stored value), but
in neither case is the branch followed, so there is no race.
> The next step is to change x.store(-1, release) to x.store(+1,
> release) :
>
> int data; //= 0
> atomic<int> x; //= 0
>
> thread 1:
> ------------
> if (x.load(relaxed) > 0)
> data = 1;
>
> thread 2:
> ------------
> data = 2;
> x.store(+1, release);
>
> This just ought to be data-race-free as well!!!
I don't see why. The load is relaxed, so it is unordered. If it reads
"+1", there is still no happens-before relationship between the two
stores to data, so we have a race.
If you need the ordering, use memory_order_acquire for the load.
That's what it's there for. If there was a data dependency you could
use memory_order_consume instead.
It is unfortunate that the C++0x atomics don't neatly map to the most
efficient instruction sequence on any particular architecture, but not
all current (and future) architectures have the same set of
constraints and guarantees.
Anthony
--
Anthony Williams
Custom Software Development | http://www.justsoftwaresolutions.co.uk
Just Software Solutions Ltd, Registered in England, Company Number 5478976.
Registered Office: 15 Carrallack Mews, St Just, Cornwall, TR19 7UL, UK
More information about the cpp-threads
mailing list