Skip to content

Instantly share code, notes, and snippets.

@thedeemon
Last active November 20, 2015 17:09
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 thedeemon/7e99d3bf466606e5e8e5 to your computer and use it in GitHub Desktop.
Save thedeemon/7e99d3bf466606e5e8e5 to your computer and use it in GitHub Desktop.
import std.stdio, core.thread, std.concurrency, std.datetime, core.atomic;
class Chan(T) {
T store;
bool haveData = false;
this() {}
void send(T v) shared {
while(haveData) yield();
store = v;
haveData = true;
yield();
}
T receive() shared {
while (!haveData) yield();
haveData = false;
return store;
}
}
void player(string name, shared Chan!int from, shared Chan!int to) {
while(true) {
int v = from.receive();
to.send(v+1);
if (v >= 100000) { ownerTid.send(v); return; }
}
}
void main(string[] argv) {
scheduler = new FiberScheduler;
StopWatch sw;
sw.start();
scheduler.start({
auto c1 = new shared Chan!int;
auto c2 = new shared Chan!int;
auto p1 = spawn(&player, "Anne", c1, c2);
auto p2 = spawn(&player, "Bob", c2, c1);
c1.send(1); // send the ball
while(!receiveTimeout(0.msecs, (int v) { writeln(v); })) //wait for them to finish
yield();
});
sw.stop();
writeln("time: ", sw.peek.msecs, " ms");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment