You could use Lazy<T>
class. By default it will support LazyThreadSafetyMode.ExecutionAndPublication
.
Or you can do like this:
Snippet from Queue<T>
:
object SyncRoot
{
get
{
if (_syncRoot == null)
Interlocked.CompareExchange<object>(ref _syncRoot, new object(), null);
return _syncRoot;
}
}
As Interlocked
is a CPU-Level instruction, I think it would be supported by other languages. And this pattern can be used without Lazy<T>
class.
Now when two threads first reach line
if (_syncRoot == null)
The first thread calls Interlocked.CompareExchange
will assign _syncRoot
with new Object()
, the latter will do nothing because now _syncRoot
would fail to compare with comparand null
.