Unsynchronized int access from threads
aliak
something at something.com
Thu Jun 18 22:12:14 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
If there's no alignment hanky panky (e.g. struct packing), and
you're on x86-64, you have your guarantee - as reading aligned
words are atomic. If you want portability then there's no
guarantee.
Steven's case could certainly happen if a value crosses a word
boundary on a platform that doesn't guarantee atomic reads/writes.
I was confirming things and found this which was a fun little
read:
https://preshing.com/20130618/atomic-vs-non-atomic-operations/
More information about the Digitalmars-d
mailing list