Thanks Martin. I am still not 100% sure this is thread safe because of the lack of a read barrier on the first null test. Is it possible to test "not null" and still only have a partially written pointer in Singleton.value pointing to junk?

Win32 makes 32-bit assignments atomic on properly-aligned 32-bit variables, but are all CLR references always properly-aligned?

Or, since we don't have a read barrier, is it possible that we get the correct pointer, but that pointer is pointing to some other stale object in this threads heap (because no read barrier to sync the cache)?

Either way, it would be interesting to see some explicit text on those questions. Maybe you could post your pattern to the C# ng to see what shakes out.

I noticed MS makes "value" a volatile explicitly for the assignment issue (I think).
http://msdn.microsoft.com/ librar...tonInCsharp.asp

Cheers!

--William


I am posting this specific pattern because from what I have read it seems to be the most comprehensive and accurate one.
First I would like to point that this is not my pattern (you know – if it works it is mine, if it not - I do not know who wrote it ))). This pattern is from Brad Abrams’s article “volatile and MemoryBarrier()...”. You can find the links in my post. In the comments there is explained also why you there is not necessary to have read barrier on the first read. But since you’ve asked, here it is . We need MemoryBarrier only to ensure that another thread won’t see the assignment of newVal object to Singleton.value field before actually instantiating the class. There is no need for read barrier in checking Singleton.value for null. This double checking for null value is intended only to safe useless locking before it is actually needed. But as I write this I understood what you mean. There can be a problem if assigning to Singleton.value comes before checking for null statement and that would be the case you describe. However the problem can be solved if there is acquire barrier between the checking for null and assignment of Singleton.value. Since MemoryBarrier is both acquire and release barrier this problem is no longer problem I think . Actually this case is also described in the comments for Brad Abrams’s post.
Using volatile is also an option, but what volatile actually does is to put full memory barrier every time you access it. It is a little performance hit.
Why do you need CLR references to be properly aligned? I do not know what the case here is.
Thanks for your comment. It really helped me to better understand the pattern.


Thanks Martin. I have read that blog before and read it again after you linked it. Still, I still think there may be an issue here. Maybe not, but it would be cool to see the thread on the c# ng. A few their may know for sure. Fun stuff. Cheers.




Name:

Email:

URL:

Comment:  ? 


 

Commenting by HaloScan