Singleton: Difference between revisions
Content added Content deleted
(→Thread-safe: forgot to close the handle) |
(+D) |
||
Line 111: | Line 111: | ||
@end |
@end |
||
</pre> |
</pre> |
||
=={{header|D}}== |
|||
<d>module singleton ; |
|||
import std.stdio ; |
|||
import std.thread ; |
|||
import std.random ; |
|||
import std.c.time ; |
|||
class Dealer { |
|||
static Dealer me ; |
|||
static Dealer Instance() { |
|||
synchronized { // this part of code can only be executed by one thread a time |
|||
if(me is null) { |
|||
// some delay so that other threads has chance to call this synchronized code |
|||
for(int i = 0 ; i < 6 ; i++) { |
|||
writefln("...calling Dealer... ") ; |
|||
msleep(rand() & 2048) ; |
|||
} |
|||
me = new Dealer ; |
|||
} |
|||
} |
|||
return me ; |
|||
} |
|||
static string[] str = ["(1)Enjoy", "(2)Rosetta", "(3)Code"] ; |
|||
int state ; |
|||
private this() { |
|||
writefln(">>Dealer is called to come in!") ; |
|||
state = str.length - 1 ; |
|||
} |
|||
Dealer nextState() { |
|||
synchronized { |
|||
state = (state + 1) % str.length ; |
|||
} |
|||
return this ; |
|||
} |
|||
string toString() { return str[state] ; } |
|||
} |
|||
class Coder : Thread { |
|||
string name_ ; |
|||
Coder hasName(string name) { name_ = name ; return this ; } |
|||
override int run() { |
|||
msleep(rand() & 512) ; |
|||
writefln(">>%s come in.", name_) ; |
|||
Dealer single = Dealer.Instance ; |
|||
msleep(rand() & 512) ; |
|||
for(int i = 0 ; i < 3 ; i++) { |
|||
writefln("%9s got %-s", name_, single.nextState) ; |
|||
msleep(rand() & 1024) ; |
|||
} |
|||
return 0 ; |
|||
} |
|||
} |
|||
void main() { |
|||
Coder x = new Coder ; |
|||
Coder y = new Coder ; |
|||
Coder z = new Coder ; |
|||
x.hasName("Peter").start() ; |
|||
y.hasName("Paul").start() ; |
|||
z.hasName("Mary").start() ; |
|||
x.wait ; y.wait ; z.wait ; |
|||
}</d> |
|||
Sample Output: |
|||
<pre>>>Peter come in. |
|||
...calling Dealer... |
|||
...calling Dealer... |
|||
...calling Dealer... |
|||
...calling Dealer... |
|||
...calling Dealer... |
|||
>>Paul come in. |
|||
>>Mary come in. |
|||
...calling Dealer... |
|||
>>Dealer is called to come in! |
|||
Mary got (1)Enjoy |
|||
Paul got (2)Rosetta |
|||
Mary got (3)Code |
|||
Peter got (1)Enjoy |
|||
Paul got (2)Rosetta |
|||
Mary got (3)Code |
|||
Paul got (1)Enjoy |
|||
Peter got (2)Rosetta |
|||
Peter got (3)Code</pre> |