Multi-Thread message passing approach

Charles Hixson via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Aug 15 08:22:58 PDT 2016


I misunderstood the problem.  The problem was that a dynamically sized 
array cannot be sent as a message.  So this works:

import   std.concurrency;
import   std.stdio;

import   core.thread;

enum  tidMax   =  10;
struct   Start {  int   tidCnt   =  0; Tid[tidMax] tids; }
struct   Msg   {  int   orig; int   dest; }
struct   Done  {  int   dummy =  0; }

void  worker (int ndx)
{
    writeln  ("worker ", ndx, " spawned");
    Start start =  receiveOnly!(Start)();
    Tid[] tids;
    foreach (i; 0 .. start.tidCnt)   {  tids  ~= start.tids[i]; }
    writeln  ("worker ", ndx, " got tidList");
    for   (int i = 0; i < 3;   i++)
    {  if (i != ndx)
       {  Msg msg  =  Msg(ndx, i);
          send (tids[i], msg);
       }
    }
    writeln  ("worker ", ndx, " sent messages");
    bool  done  =  false;
    while (!done)
    {  receive
       (  (Msg msg)   {  writeln ("msg from: ", msg.orig, ", to: ", 
msg.dest); },
          (Done d) {  done = true;   }
       );
    }
    writeln ("worker ", ndx, " is done");
}

void  main()
{
    Start start;
    Done  done;
    for   (int i = 0; i < 3;   i++)
    {  auto tid =  spawn (&worker, i);
       start.tids[start.tidCnt++] =  tid;
    }
    foreach (i; 0 .. start.tidCnt)   {  send (start.tids[i], start); }
    Thread.sleep (1000.msecs);
    foreach (i; 0 .. start.tidCnt)   {  send (start.tids[i], done); }
    Thread.sleep (1000.msecs);
    writeln ("main is done");
}



More information about the Digitalmars-d-learn mailing list