On 02/09/2015 11:46 AM, Ali Çehreli wrote:

> threads normally start one [or] more worker threads and
> send tasks to those threads

Accordingly, the following program uses just three threads:

import std.stdio;
import std.concurrency;
import std.conv;
import core.thread;

struct Terminate
{}

void main() {

    auto square_tid = spawn(&square);

    foreach (int num; 1..100) {
        square_tid.send(num);
        auto square = receiveOnly!string();
        writeln(square);
    }

    square_tid.send(Terminate());
}

void square() {
    auto i = 0;
    bool done = false;
    auto stringWorker = spawn(&stringConverter, ownerTid);

    while (!done) {
        receive (
            (Terminate message) {
                stringWorker.send(message);
                done = true;
            },

            (int num) {
                auto square = num * num;
                writeln("sqaure : Comes in with " ,
                        num , " for " , ++i , " time");
                stringWorker.send(square);
            });
    }
}

void stringConverter(Tid destination) {
    auto i = 0;
    bool done = false;

    while (!done) {
        receive (
            (Terminate message) {
                done = true;
            },

            (int num) {
                auto stringified = num.to!string;

                writeln("string : Comes in with ",
                        num, " for " , ++i , " time");
                destination.send(stringified);
            });
    }
}

Ali

Reply via email to