Threadsafe singleton using volatile,synchonized
Sean Kelly
sean at f4.ca
Sun May 27 08:50:00 PDT 2007
BLS wrote:
> Thanks Sean, indeed a very interesting thread.
> From 2004;It is really worth to browse the archives!
> What is the reason/rationale for using volatile in this way ?
In D, 'volatile' is a statement rather than a storage attribute. So you
need to use it explicitly in places where you want to restrict
compiler-based code movement. In the code below, a temporary is used to
ensure that Singleton (s) is fully constructed before s is set,
otherwise the compiler could theoretically do this:
s = new Singleton;
// translates to
s = allocate_memory for Singleton;
s.ctor();
The presence of 'volatile' is to ensure that the compiler doesn't try to
eliminate 'tmp' entirely and just use 's', since that would be a legal
optimization.
> Another Question:
> Is something like this available
>
> CriticalSectionBegin()
> {
> // Your Single thread code goes here
> }
> CriticalSectionEnd()
Other than synchronized? Could you provide more detail?
Sean
More information about the Digitalmars-d
mailing list