.NET 4自旋锁 [英] .NET 4 SpinLock

查看:111
本文介绍了.NET 4自旋锁的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的测试code(F#)没有返回结果,我期望:

The following test code (F#) is not returning the result I'd expect:

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

我期望的自旋锁相互排斥柜台,因此,它返回100万计数,但是,相反,它会返回较小的值,如果没有相互排除发生。

I'd expect the SpinLock to mutually exclude the counter and, therefore, for it to return counts of 1,000,000 but, instead, it returns smaller values as if no mutual exclusion is occurring.

任何想法有什么不对?

推荐答案

编辑: 斯蒂芬·斯文森有办法直接访问下方的裁判风格自旋锁。 返回结构所以不宜在这种情况下使用的副本。

Stephen Swensen has a way to directly access a ref style SpinLock below. ! returns a copy of structs so should not be used in this case.

您可以在它的工作原理类包装自旋锁(我试图用一个静态的,一成不变的自旋锁都无济于事)

You can wrap SpinLock in a class it works (I tried using a static and immutable SpinLock to no avail)

type SpinLockClass() =
    let s = System.Threading.SpinLock(false)
    member x.Enter locked = s.Enter(locked)
    member x.Exit() = s.Exit()

let safeCount() =
  let n = 1000000
  let counter = ref 0
  let spinlock = SpinLockClass()
  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

这篇关于.NET 4自旋锁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆