Passing messages with std.concurrency
Passing data to and from threads correctly can be difficult to get right. Phobos provides an abstraction to make passing messages much simpler.
How to do it…
Execute the following steps to pass messages with std.concurrency
:
Use the command
import std.concurrency;
.Spawn a thread with an independent function. You may pass arguments to the function as long as they can be safely shared across threads. You can pass an instance of
thisTid
to the child thread so that it knows who its parent is for communication, or the child can usestd.concurrency.ownerTid
to get the handle of the thread that spawned it.Define a struct to serve as a message to communicate across threads.
Send a message with the
send
function and your struct from the child thread when it has completed its task.In the parent thread, use
receive
with a delegate to handle your message type.Add additional threads to the program as needed or more message handlers to the receive call if you want to...