5

When an immutable object is new'ed up in one thread, and shared in second thread (say as a field of shared object), shouldn't second thread synchronize?

Thread1:
=========
 x = new SomeObject()

Thread2
=========
if (x != null)
 x.DoSomething()

Should there be a memory barrier before x.DoSomething()? is it possible that the assignment to x in the first thread is never visible to the second thread? What is the safe publication pattern for .NET?

skaffman
  • 398,947
  • 96
  • 818
  • 769
drr
  • 91
  • 1
  • 4

1 Answers1

2

Yes, it is possible that thread 2 will never see a non-null value of x with the code you have written (depending on how the code is optimized). You don't need an explicit memory barrier. Just declare x as volatile.

Peter Ruderman
  • 12,241
  • 1
  • 36
  • 58
  • ok. Is there any safe publication related info/documentation for .NET? – drr Mar 14 '11 at 20:52
  • 1
    I guess it depends on exactly what you want to do. I'd look into the Parallel Patterns library on MSDN as a starting point. Aside from that, you pretty much just have the synchronization primitives. You could also check out Joe Duffy's web log. He talks quite a bit about the finer points of locking and parallel data access. – Peter Ruderman Mar 14 '11 at 21:53
  • I don't know of any documentation that says so, but to be safe would require memory fences on the write and the read. Which you can get through several ways as mentioned, locks, volatile, Thread.VolatileRead/Write, explicit calls to MemoryBarrier. See [threading in c#](http://www.albahari.com/threading/part4.aspx#_Memory_Barriers_and_Volatility) for more info – BrandonAGr Mar 15 '11 at 01:13