Last active
February 5, 2022 09:09
-
-
Save DeivAstra/bdde9746e661092bbec846ebba197093 to your computer and use it in GitHub Desktop.
Singleton examples (D language)
This file contains hidden or 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
| module singleton_test; | |
| import std.stdio; | |
| import core.thread.osthread; | |
| void main() { | |
| testSingletonMultithread(); | |
| } | |
| class Singleton1 { | |
| private static shared Singleton1 instance; | |
| private shared this() { | |
| writefln("this!%s", this); | |
| } | |
| synchronized static Singleton1 getInstance() { | |
| if(!instance) instance = new shared(Singleton1)(); | |
| return cast(Singleton1) instance; | |
| } | |
| synchronized static shared(Singleton1) getSharedInstance() { | |
| if(!instance) instance = new shared(Singleton1)(); | |
| return instance; | |
| } | |
| } | |
| class Singleton2 { | |
| private static shared Singleton2 instance; | |
| private this() { | |
| writefln("this!%s", this); | |
| } | |
| static Singleton2 getInstance() { | |
| synchronized(Singleton2.classinfo) { | |
| if(!instance) instance = cast(shared) new Singleton2(); | |
| return cast(Singleton2) instance; | |
| } | |
| } | |
| } | |
| class Singleton3 { | |
| private static bool instantiated_; | |
| private __gshared Singleton3 instance_; | |
| private this() { | |
| writefln("this!%s", this); | |
| } | |
| static Singleton3 getInstance() { | |
| if (!instantiated_) { | |
| synchronized(Singleton3.classinfo) { | |
| if (!instance_) instance_ = new Singleton3(); | |
| instantiated_ = true; | |
| } | |
| } | |
| return instance_; | |
| } | |
| } | |
| void testSingletonMultithread() { | |
| const count = 30; | |
| foreach(int i; 1..count) { | |
| new Thread({ | |
| Singleton1 s1 = Singleton1.getInstance(); | |
| // or | |
| shared Singleton1 s2 = Singleton1.getSharedInstance(); | |
| writefln("%s#%s", s1, s1.toHash()); | |
| }).start(); | |
| } | |
| foreach(int i; 1..count) { | |
| new Thread({ | |
| Singleton2 s = Singleton2.getInstance(); | |
| writefln("%s# %s", s, s.toHash()); | |
| }).start(); | |
| } | |
| foreach(int i; 1..count) { | |
| new Thread({ | |
| Singleton3 s = Singleton3.getInstance(); | |
| writefln("%s# %s", s, s.toHash()); | |
| }).start(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment