Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
740 views
in Technique[技术] by (71.8m points)

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

question from:https://stackoverflow.com/questions/66047448/thread-safe-option-in-f

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...