I've come across a situation where a ref cell containing a boolean allows me to quite conveniently solve a problem of telling a spin-waiting loop to stop spin-waiting. I need to mark this flag as volatile (i.e. [<VolatileField>]
) but such a field needs to be mutable
according to the compiler, which is exactly what I don't want the reference to be -- I want its contents to be mutable, not the reference cell field itself.
Is there a standard way of telling a ref cell to mark its contents as volatile or do I need to roll my own ref cell (i.e. copy-paste the standard ref cell definition with [<VolatileField>]
stuck just above mutable contents
)? Well, correcting that for the fact that you cannot mark record fields as volatile...
Volatile.
or Interlocked.
methods just work fine with ref cells:
open System.Threading
let refCell = ref 0
Volatile.Write(refCell, 42)
let fortyTwo = Volatile.Read(refCell)
You do not even need &
or !
before ref cells variable names, they are already references. Volatile
and Interlocked
methods are easier to reason about than [<VolatileField>]
as described here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With