Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F#: is there a way to mark a ref cell contents as volatile?

Tags:

f#

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...

like image 259
mt99 Avatar asked Jul 26 '16 10:07

mt99


1 Answers

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.

like image 146
V.B. Avatar answered Oct 09 '22 16:10

V.B.