Question regarding freshness of volatile reading of a value written with Interlocked #97009
Replies: 1 comment
-
Tagging subscribers to this area: @mangod9 Issue DetailsLet's look at this code
This class allows its user to add tasks to the internal list. When the I'm not sure about the guarantees applied to this line: } while ((bag = _bag) != oldBag); Image that I saw many different opinions on SO about different between I know that this code may be rewritten without
|
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Let's look at this code
This class allows its user to add tasks to the internal list. When the
WaitAllAvailableAsync
is called, all currently added tasks are removed from the list and awaited. This may be used as a barrier mechanism to wait for all already started incoming requests to complete (without blocking adding newer requests). Both methods are thread safe and can be used from any number of threads.I'm not sure about the guarantees applied to this line:
Image that
Interlocked.Exchange(
have already executed at this point and another instance of bag was written. Does volatile read of_bag
really guarantees seeing the new value? WouldInterlocked.CompareExchange(ref _bag, null, null)
provide better guarantees?I saw many different opinions on SO about the difference between
Interlocked
andvolatile
non-caching guarantees. Some people say thatvolaile
only prevents reordering, others say that it also ensures reading somewhat fresh value but it can be stale by a few milli/nanoseconds. For the code above reading any stale value can lead to that the task will be added to an already discarded_bag
instance and thus the task will never be awaited. I'm not sure whom to believe so I decided to ask here.I know that this code may be rewritten without
volatile
by usingConcurrentQueue
but here I'm trying to understand specifically the behavior ofvolatile
read in this example.Similar issue #67330 doesn't have the answer suitable here.
Beta Was this translation helpful? Give feedback.
All reactions