Skip to content

Instantly share code, notes, and snippets.

@yamadapc
Last active June 1, 2016 19:43
Show Gist options
  • Save yamadapc/50921b43b012d71ac190b4573e894778 to your computer and use it in GitHub Desktop.
Save yamadapc/50921b43b012d71ac190b4573e894778 to your computer and use it in GitHub Desktop.
import std.stdio;
import std.concurrency;
import core.thread;
void spawnedFunc(Tid ownerTid)
{
// Receive a message from the owner thread.
while (!receiveTimeout(1.dur!"seconds",
(int i) {
writeln("Received the number ", i);
}
)) {
writefln("spawnedFunc - LOGICAL-THREAD: %s OS-THREAD: %s", thisTid, Thread.getThis().id);
stdout.flush();
}
// Send a message back to the owner thread
// indicating success.
send(ownerTid, true);
}
void main()
{
auto runMain() {
// Start spawnedFunc in a new thread.
auto childTid = spawn(&spawnedFunc, thisTid);
// Send the number 42 to this new thread.
for(int i = 0; i < 10; i++) {
writefln("main - LOGICAL-THREAD: %s OS-THREAD: %s", thisTid, Thread.getThis().id);
stdout.flush();
yield();
Thread.sleep(1.dur!"seconds");
}
send(childTid, 42);
// Receive the result code.
auto wasSuccessful = receiveOnly!(bool);
assert(wasSuccessful);
writeln("Successfully printed number.");
};
version (fibers) {
writeln("Using FiberScheduler");
scheduler = new FiberScheduler();
scheduler.start(&runMain);
} else {
writeln("Using ThreadScheduler");
runMain();
}
}
@yamadapc
Copy link
Author

yamadapc commented Jun 1, 2016

rdmd -version=fibers concurrency.d
rdmd concurrency.d

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment