Last active
April 26, 2020 14:00
-
-
Save Zardoz89/c6396a1609e9b20ab6d0bf0ed15a4444 to your computer and use it in GitHub Desktop.
Dlang templates to generate singlenton boilerplate
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import std; | |
/** | |
* Implementes the TLS fast thread safe singleton | |
* Source: http://p0nce.github.io/d-idioms/#Leveraging-TLS-for-a-fast-thread-safe-singleton | |
*/ | |
mixin template Singleton(T) | |
{ | |
mixin(" | |
private static bool instantiated_; | |
private __gshared T instance_; | |
public static T get() @trusted | |
{ | |
if (!instantiated_) { | |
synchronized (T.classinfo) { | |
if (!instance_) { | |
instance_ = new T(); | |
} | |
instantiated_ = true; | |
} | |
} | |
return instance_; | |
} | |
"); | |
} | |
/** | |
* Implementes a singleton over TLS . Unsafe for multi-thread usage. | |
*/ | |
mixin template TlsSingleton(T) | |
{ | |
mixin(" | |
private static T instance_; | |
public static T get() @trusted | |
{ | |
if (!instance_) { | |
instance_ = new T(); | |
} | |
return instance_; | |
} | |
"); | |
} | |
class Singleton_ | |
{ | |
private this() {} | |
mixin Singleton!Singleton_; | |
public: | |
int x; | |
override string toString() @safe | |
{ | |
import std.conv : to; | |
return "Singleton_(" ~ to!string(this.x) ~ ")"; | |
} | |
} | |
class TlsSingleton_ | |
{ | |
private this() {} | |
int x; | |
mixin TlsSingleton!TlsSingleton_; | |
override string toString() @safe | |
{ | |
import std.conv : to; | |
return "TlsSingleton_(" ~ to!string(this.x) ~ ")"; | |
} | |
} | |
void main() | |
{ | |
auto single = Singleton_.get(); | |
single.x = 3; | |
writeln(single); | |
writeln(Singleton_.get()); | |
auto tls = TlsSingleton_.get(); | |
tls.x = 42; | |
writeln(tls); | |
writeln(TlsSingleton_.get()); | |
import core.thread.osthread; | |
new Thread({ | |
writeln("A thread"); | |
Singleton_.get().x = 333; | |
writeln(Singleton_.get()); | |
auto s2 = Singleton_.get(); | |
writeln(s2); | |
writeln(single); | |
auto tls2 = TlsSingleton_.get(); | |
tls2.x = 666; | |
writeln(tls2); | |
writeln(TlsSingleton_.get()); | |
writeln(tls); // TlsSingleton_(42) as is a difent instance | |
}).start(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment