On 05/27/2010 01:37 PM, Max Samukha wrote:


module a;
mixin template Foo()
{
static immutable Object foo;
shared static this()
{
foo = cast(immutable)new Object;
}
}

----
module b;
import a;
import c;

mixin Foo;

----
module c;
import a;
import b;

mixin Foo;

In this scenario one is forced to avoid static constructors by lazily
initializing foo and using some kind of synchronization, which should be
absolutely unnecessary and sometimes is not tolerable.


Ok, I've just thought of a way to avoid synchronization (using __gshared for simplicity):

module a;
mixin template Foo()
{
    static __gshared Object foo; // shared foo
    static Object tlFoo; // thread-local foo

    Object getFoo()
    {
        if (!tlFoo)
        {
            synchronized(lock)
            {
                if (!foo)
                    foo = new Object;
            }
            tlFoo = foo;
        }
        return tlFoo;
    }
}

There is still unnecessary overhead of accessing and testing the thread-local variable.


Reply via email to