以下测试代码 (F#) 未返回我期望的结果:
let safeCount() =
let n = 1000000
let counter = ref 0
let spinlock = ref <| SpinLock(false)
let run i0 i1 () =
for i=i0 to i1-1 do
let locked = ref false
try
(!spinlock).Enter locked
if !locked then
counter := !counter + 1
finally
if !locked then
(!spinlock).Exit()
let thread = System.Threading.Thread(run 0 (n/2))
thread.Start()
run (n/2) n ()
thread.Join()
!counter
我期望的是SpinLock
互斥计数器,因此它返回 1,000,000 的计数,但相反,它返回较小的值,就好像没有发生互斥一样。
任何想法有什么问题吗?
SpinLock 结构被复制的原因是!是一个函数:当作为参数传递给函数或从函数返回时(或任何其他类型的赋值),结构会被复制。但是,如果您访问contents直接引用单元格,不进行复制。
let safeCount() =
let n = 1000000
let counter = ref 0
let spinlock = ref <| SpinLock(false)
let run i0 i1 () =
for i=i0 to i1-1 do
let locked = ref false
try
spinlock.contents.Enter locked
if !locked then
counter := !counter + 1
finally
if !locked then
spinlock.contents.Exit()
let thread = System.Threading.Thread(run 0 (n/2))
thread.Start()
run (n/2) n ()
thread.Join()
!counter
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)