1 /*******************************************************************************
2         copyright:      Copyright (c) 2008. Fawzi Mohamed
3         license:        BSD style: $(LICENSE)
4         version:        Initial release: Sep 2008
5         author:         Fawzi Mohamed
6 *******************************************************************************/
7 module tango.math.random.engines.Sync;
8 private import Integer = tango.text.convert.Integer;
9 import tango.core.sync.Mutex: Mutex;
10 
11 /+ Makes a synchronized engine out of the engine E, so multiple thread access is ok
12 + (but if you need multiple thread access think about having a random number generator per thread)
13 + This is the engine, *never* use it directly, always use it though a RandomG class
14 +/
15 struct Sync(E){
16     E engine;
17     Mutex lock;
18     
19     enum int canCheckpoint=E.canCheckpoint;
20     enum int canSeed=E.canSeed;
21     
22     void skip(uint n){
23         for (int i=n;i!=n;--i){
24             engine.next();
25         }
26     }
27     ubyte nextB(){
28         synchronized(lock){
29             return engine.nextB();
30         }
31     }
32     uint next(){
33         synchronized(lock){
34             return engine.next();
35         }
36     }
37     ulong nextL(){
38         synchronized(lock){
39             return engine.nextL();
40         }
41     }
42     
43     void seed(scope uint delegate() r){
44         if (!lock) lock=new Mutex();
45         synchronized(lock){
46             engine.seed(r);
47         }
48     }
49     /// writes the current status in a string
50     immutable(char)[] toString(){
51         synchronized(lock){
52             return "Sync"~engine.toString();
53         }
54     }
55     /// reads the current status from a string (that should have been trimmed)
56     /// returns the number of chars read
57     size_t fromString(const(char[]) s){
58         size_t i;
59         assert(s[0..4]=="Sync","unexpected kind, expected Sync");
60         synchronized(lock){
61             i=engine.fromString(s[i+4..$]);
62         }
63         return i+4;
64     }
65 }