A breach of immutability due to memory implicit conversions to immutable without synchronisation, maybe??

Steven Schveighoffer schveiguy at gmail.com
Sun Nov 11 20:48:31 UTC 2018


On 11/11/18 3:47 PM, Steven Schveighoffer wrote:
> On 11/11/18 2:21 PM, John Colvin wrote:
>> Take a look at this (I think?) supposed-to-be-thread-safe code 
>> according to the rules of D:
>>
>> import std.stdio;
>> import core.thread;
>> import core.atomic;
>>
>> int* foo() pure
>> {
>>      auto ret = new int;
>>      *ret = 3;  // MODIFY
>>      return ret;
>> }
>>
>> shared immutable(int)* g;
>>
>> void bar()
>> {
>>      immutable(int)* d = null;
>>      while (d is null)
>>          d = g.atomicLoad;
>>      assert(*d == 3); // READ
>>      assert(*d == 3); // READ AGAIN
>> }
>>
>> void main()
>> {
>>      auto t = new Thread(&bar).start();
>>      immutable(int)* a = foo();
>>      g.atomicStore(a);
>>      t.join;
>> }
>>
>> What stops the CPU executing this such that MODIFY happens between 
>> READ and READ AGAIN ?

Wait, wouldn't the atomicStore create a barrier, such that all the code 
before it must execute?

-Steve


More information about the Digitalmars-d mailing list