Worker is not finished while sending message to intermediate worker

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Feb 9 12:11:09 PST 2015


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



More information about the Digitalmars-d-learn mailing list