Book Image

D Cookbook

By : Adam Ruppe
Book Image

D Cookbook

By: Adam Ruppe

Overview of this book

Table of Contents (21 chapters)
D Cookbook
Credits
Foreword
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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:

  1. Use the command import std.concurrency;.

  2. 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 use std.concurrency.ownerTid to get the handle of the thread that spawned it.

  3. Define a struct to serve as a message to communicate across threads.

  4. Send a message with the send function and your struct from the child thread when it has completed its task.

  5. In the parent thread, use receive with a delegate to handle your message type.

  6. Add additional threads to the program as needed or more message handlers to the receive call if you want to...