Channels in D Programming Language

In D, we can use channels to connect concurrent threads. Channels allow you to send values from one thread and receive those values in another thread.

import std.stdio;
import std.concurrency;

void main()
{
    // Create a new channel using `new Tid`
    // Channels in D are typed by the values they convey
    auto tid = spawn(&worker);

    // Send a value to the channel using `send`
    send(tid, "ping");

    // Receive a value from the channel using `receiveOnly`
    string msg = receiveOnly!string();
    writeln(msg);
}

void worker()
{
    // Receive the message and send it back
    auto msg = receiveOnly!string();
    ownerTid.send(msg);
}

When we run the program, the “ping” message is successfully passed from one thread to another via our channel.

$ dmd channels.d
$ ./channels
ping

In D, sends and receives are blocking operations by default. This property allows us to wait at the end of our program for the “ping” message without having to use any other synchronization mechanism.

D’s concurrency model uses threads and message passing, which is similar to the concept of goroutines and channels in other languages. The spawn function is used to create a new thread, and send and receiveOnly are used for inter-thread communication.