4

It looks like the mono implementation has no MemoryBarrier calls inside the ReaderWriterLockSlim methods. So when I make any changes inside a write lock, I can receive old cached values in another thread which uses a read lock.

Is it really possible? Should I insert MemoryBarrier before and after the code inside Read and Write lock?

Vlad
  • 3,001
  • 1
  • 22
  • 52

2 Answers2

5

Looking at (what I think is) the mono source, the Mono ReaderWriterLockSlim is implemented using Interlocked calls.

These calls include a memory barrier on x86, so you shouldn't need to add one.

Community
  • 1
  • 1
Peter Wishart
  • 11,600
  • 1
  • 26
  • 45
  • 1
    There are some CPUs that have a CAS without memory barriers, but they're pretty rare, and I think even they have CAS forms with memory barriers, but just also CAS without for when you really want the ultimate in concurrency. – Jon Hanna Jan 14 '14 at 22:14
2

As Peter correctly points out, the implementation does introduce a memory barrier, just not explicitly.

More generally: the C# language specification requires that certain side effects be well ordered with respect to locks. Though that rule only applies to locks entered with the C# lock statement, it would be exceedingly strange for a provider of a custom locking primitive to make a locking object that did not follow the same rules. You are wise to double-check, but in general you can assume that if its a threading primitive then it has been designed to ensure that important side effects are well-ordered around it.

Eric Lippert
  • 647,829
  • 179
  • 1,238
  • 2,067