On Saturday, 4 June 2022 at 21:33:30 UTC, David Nadlinger wrote:
>On 2 Jun 2022, at 7:56, Johan via digitalmars-d-ldc wrote:
>atomicFence
only works for ordering memory operations on a single thread, not ordering between threads.
atomicFence
should work across threads as well; it inserts actual processor fences as necessary, in addition to the requisite effect on compiler optimisations.
What I meant to say is that the fence only works for ordering memory operations of the thread that contains the fence, as observable by other threads. Indeed you use it to coordinate between threads.
If thread A has a fence somewhere, then that fence orders the memory operations of thread A that thread B will observe. So you can use variables from thread A in thread B, for example: if (value_is_ok_flag) foo(value);
. The fence in thread A (between writing value
and ok_flag
) prevents that ok_flag==true
is observed in thread B before the new value
value is observed.
Because the OP issue is not a thread synchronization issue, but a re-read optimization (only need to read variable once, instead of upon every loop iteration), the atomic fence is likely not to work. I think the atomicLoad works because it is both volatile
and atomic
.
cheers,
Johan