I know this topic has been pounded as I have read gillions of posts on SO as well as elsewhere about it, but I have yet to find a definitive answer, so my apologies if you are offended by this seeming redundancy.
I have a situation where there is a write-once, read-millions resource. The resource is extremely expensive to create and the contention on the write-lock could be very high as well. Furthermore, I cannot predict what processor this will be run on and so I do not know what the memory-model will be underneath. I am compiling 3 versions of the assembly built in .NET 3.5, .NET 4.0, and Mono 2.10.
Because of the high-contention for the resource, I need to make this as efficient as possible and would like to use a lock-free pattern, at least for the reads. I understand the double lock check pattern for creating the resource, but there has been disagreement over whether or not it works (on all processors) due to the access of _resource outside the memory barrier. Do I need to use volatile on the _resource field? Is a ReaderWriterLockSlim a better fit for this scenario? What other questions should I be asking?
if(_resource == null)
{
lock(_locker)
{
if(_resource == null)
{
//create resource here...
}
}
}
In addition, there will be a number of these:
if(_resource == null)
{
return _resourceDefault;
}
return _resource.GetSomething();