.NET 4 SpinLock

Posted by Jon Harrop on Stack Overflow See other posts from Stack Overflow or by Jon Harrop
Published on 2010-06-11T00:20:53Z Indexed on 2010/06/11 0:22 UTC
Read the original article Hit count: 550

Filed under:
|

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

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.

Any ideas what's wrong?

© Stack Overflow or respective owner

Related posts about .NET

Related posts about F#