Milosz Krajewski
Milosz Krajewski

Reputation: 1210

byref reference to reference cell's value

I stumbled upon such problem. I need a function which will know how many times it was called. It needs to be thread safe so I would like to increase the counter using Interlocked.Increment (no lock as lock in this case takes away all the performance gain related to multi-threading). Anyway, the problem is syntactic: how can I get reference to value in reference cell (&!counter)?

let functionWithSharedCounter = 
    let counter = ref 0
    fun () ->
        // I tried the ones below:
        // let index = Interlocked.Increment(&counter)
        // let index = Interlocked.Increment(&!counter)
        // let index = Interlocked.Increment(&counter.Value)
        printfn "captured value: %d" index

functionWithSharedCounter ()
functionWithSharedCounter ()
functionWithSharedCounter ()

Cheers,

Upvotes: 0

Views: 99

Answers (1)

Tomas Petricek
Tomas Petricek

Reputation: 243051

F# automatically treats values of the ref type as byref parameters, so you do not need any special syntax:

let functionWithSharedCounter = 
    let counter = ref 0
    fun () ->
        let index = Interlocked.Increment(counter)
        printfn "captured value: %d" index

You can also take a reference of a mutable field, so you could write the following too:

let index = Interlocked.Increment(&counter.contents)

This works with the filed contents, but not with counter.Value, because that is a property.

Upvotes: 2

Related Questions