[cpp-threads] [Javamemorymodel-discussion] there's a happens-before orderhere. right?

Alexander Terekhov alexander.terekhov at gmail.com
Mon Dec 15 13:32:56 GMT 2008


On Mon, Dec 15, 2008 at 12:47 PM, Anthony Williams
<anthony at justsoftwaresolutions.co.uk> wrote:
> 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.

IOW you agree that it shall not be allowed to "speculate" conditional
store (e.g. by (mis)predicting positive value for load) such that
conditional store could happen before thread 1 has actually observed
positive value in x. But that means that conditional store "happens
after" load, which is to say load "happens before" conditional
store!!!

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

See above.

regards,
alexander.



More information about the cpp-threads mailing list