Thomas
Thomas

Reputation: 12107

thread-safe option in F#

I'm trying to solve this issue (psdeudo code):

let myObject : T option = None

onEvent (fun t -> if myObject.IsSome then myObject.Value(t))

some logic (
    while forever do
        myObject <- Some T()
        // do something
        myObject <- None
        // do something

I have an object that gets created and destroyed depending on some external parameters. There is an even that is always firing that brings data to either be processed by the object, if it exists, or to just be ignored.

The issue here is that between:

if myObject.IsSome

and

myObject.Value

the state could change. Is there a mechanism to handle this? like something that could be like Option.TryGet that will either return an object, or not, in an atomic fashion?

or is there any other mechanism I can use with that?

I guess I could try to get the object value directly in a try / with section, but I was hoping for something cleaner.

Upvotes: 2

Views: 221

Answers (1)

Fyodor Soikin
Fyodor Soikin

Reputation: 80765

Take the value out of the mutable cell and save it in a local variable, then you can interact with the local variable in a thread-safe way:

onEvent (fun t -> 
    let v = myObject
    if v.IsSome then v.Value(t)
)

This works because the Option value itself is immutable. Each mutation of myObject creates a new Option value and makes myObject reference it. Reading the reference is an atomic operation.

Upvotes: 4

Related Questions