-
-
Save zorael/17b042c424cfea5ebb5f1f3120f983f4 to your computer and use it in GitHub Desktop.
where to add synchronize
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; | |
import core.thread; | |
import core.time; | |
class Foo | |
{ | |
shared string[int] bucket; | |
Tid worker; | |
auto getStringFromWorker() | |
{ | |
int i = uniform(1, int.max); | |
bucket[i] = string.init; // key assumed unique for brevity | |
const timestampBefore = Clock.currTime; | |
enum maxWait = 5.seconds; | |
worker.send(i); | |
while ((Clock.currTime - timestampBefore) < maxWait) | |
{ | |
auto inBucket = i in bucket; | |
if (inBucket && (inBucket.length > 0)) | |
{ | |
string s = *inBucket; | |
bucket.remove(i); | |
return s; | |
} | |
else | |
{ | |
// Value non-existent or still empty | |
Thread.sleep(100.msecs); | |
} | |
} | |
return null; | |
} | |
} | |
void main() | |
{ | |
auto foo = new Foo; | |
foo.bucket[0] = string.init; | |
foo.bucket.remove(0); | |
foo.worker = spawn(&workerFn, foo.bucket); | |
foreach (i; 0..10) | |
{ | |
writeln("string from worker:", foo.getStringFromWorker()); | |
} | |
} | |
void workerFn(shared string[int] bucket) | |
{ | |
bool halt; | |
while (!halt) | |
{ | |
receive( | |
(int i) | |
{ | |
//writeln("worker received request to assign value to bucket key ", i); | |
Thread.sleep(150.msecs); // simulate workload | |
bucket[i] = i.to!string; | |
}, | |
(OwnerTerminated _) | |
{ | |
halt = true; | |
} | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment