Unsynchronized int access from threads

Paul Backus snarwin at gmail.com
Thu Jun 18 16:55:26 UTC 2020


On Thursday, 18 June 2020 at 16:42:15 UTC, H. S. Teoh wrote:
> Suppose I have an int[] which may contain some zeroes, and 2 
> functions, one scans the array for zeroes but does not modify 
> it, and the other modifies array elements but never introduces 
> new zeroes (though it may write a 0 to an existing 0).  Is it 
> thread-safe to run the two functions in parallel without any 
> synchronization between them?
>
> I.e., will the first function always see zeroes where there are 
> zeroes, in spite of the 2nd function writing to the array 
> simultaneously?  Are there any hardware situations where the 
> 1st function may read a non-zero value if the 2nd function is 
> simultaneously overwriting an existing zero with another zero?  
> Or a situation where the 1st function may read a zero if the 
> 2nd function is simultaneously overwriting a non-zero value 
> with another non-zero value?
>
> Or am I playing with fire here?
>
>
> T

As long as reads and writes of `int` are atomic on the platform 
in question (which they probably are) you should be ok.

Personally, I would use core.atomic.atomic{Load,Store} just to be 
safe; they should optimize themselves away if they're not needed.


More information about the Digitalmars-d mailing list