Skip to content

Instantly share code, notes, and snippets.

@zorael

zorael/foo.d Secret

Created January 1, 2024 15:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zorael/17b042c424cfea5ebb5f1f3120f983f4 to your computer and use it in GitHub Desktop.
Save zorael/17b042c424cfea5ebb5f1f3120f983f4 to your computer and use it in GitHub Desktop.
where to add synchronize
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