synchonized? correct use? Thread-safe Singleton
BCS
ao at pathlink.com
Fri Jan 4 10:32:57 PST 2008
Reply to bls,
> BCS schrieb:
>
>> Reply to bls,
>>
>>> Do I have a THread-safe singleton ? If not HowTo.. Sorry. Sean K
>>> allready explains it to me, but I 've lost the info. :(
>>> Bjoern
>>> class Singleton(T)
>>> {
>>> public:
>>> static T instance()
>>> sychronized // according to the language spec this should
>>> work
>>> {
>>> if(_instance is null) _instance = new T;
>>> return _instance;
>>> }
>>> private:
>>> this() {}
>>> static T _instance;
>>> }
>>> class Application : Singleton!(Application)
>>> {
>>> }
>> I think this will fail because Singleton!(Application).instance()
>> will call Application's this() and that is private.
>>
>> IMHO, a better approach (that I haven't tested) would be to use a
>> mixin:
>>
>> template Singleton(T)
>> {
>> public:
>> static T instance() sychronized
>> // according to the language spec this should work
>> {
>> if(_instance is null) _instance = new T;
>> return _instance;
>> }
>> private:
>> this() {}
>> static T _instance;
>> }
>> class Application : Singleton!(Application)
>> {
>> mixin(Singleton!(typeof(this)));
>> }
> Thanks BCS,
>
> Confused ...'cause virus infected (me) not the pc
>
> class Application : Singleton!(Application)
> {
> mixin(Singleton!(typeof(this)));
> this()
> {
> return instance(this)
> }
> }
> Honk, that stinks somehow !
>
Oops, typo!!
class Application // no ": ..."
> Hope I ask not for too much, but please explain the use of the mixin
Think of a mixin as a copy/paste + macro. Instance the template (that's the
macro part) and just lump it into whatever scope you use it in (the copy/paste
part). It's a quick way to do boiler plate coding.
> Bjoern
>
More information about the Digitalmars-d-learn
mailing list