2015-03-31 32 views
0

我偶然發現了這樣的問題。我需要一個函數來知道它被調用了多少次。它需要是線程安全的,所以我想用Interlocked.Increment來增加計數器(在這種情況下鎖沒有鎖,從而消除了與多線程相關的所有性能增益)。 無論如何,問題是句法的:我怎樣才能得到參考單元格中的值(&!counter)?byref引用參考單元的值

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() 

乾杯,

回答

2

F#自動對待ref類型byref參數的值,所以你不需要任何特殊的語法:

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

你也可以採取一個可變的參考所以你也可以寫下面的內容:

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

這適用於提交的contents,但不適用於counter.Value,因爲這是屬性。

+0

這是一個恥辱,我沒有嘗試這一個。出於某種原因,我認爲ref的實現是:type ref <'a> = {mutable Value:'a},所以我甚至沒有考慮「特殊」行爲。謝謝! – 2015-03-31 15:12:34