Unsynchronized int access from threads

Steven Schveighoffer schveiguy at gmail.com
Thu Jun 18 19:07:54 UTC 2020


On 6/18/20 12:42 PM, 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?

I think it's possible there's a problem if the reads are not atomic:

Let's say a value is 0xffff0000

Thread that is looking for 0s reads the lower half of the number -> 
0x????0000

Context switches, thread 2 writes 0x0000ffff into that memory slot.

Back at the zero-scanning thread, it reads the second half -> 0x0000????

Combines with the first part, and now it sees a 0 where there isn't one.

I would agree with Paul -- make the reads/writes atomic.

-Steve


More information about the Digitalmars-d mailing list