Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does immutable object need to be accessed across memory barrier in C#?

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?

like image 926
drr Avatar asked Nov 06 '22 01:11

drr


1 Answers

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.

like image 144
Peter Ruderman Avatar answered Nov 13 '22 17:11

Peter Ruderman