Unsynchronized int access from threads

claptrap clap at trap.com
Thu Jun 18 22:00:05 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?

If you're on x86 all reads and writes are atomic if they are 
naturally aligned. IE 16 bits on 2 byte boundry, 32 bits on 4 
byte boundry, 64 bits on 64 bit boundry. (Dont think it applies 
to 128 bit regs)

Short version is you're fine as long as your ints are on 4 byte 
boundrys.

If you want unaligned atomicity you need a lock prefix.



More information about the Digitalmars-d mailing list