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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With