Multi-Thread message passing approach

Charles Hixson via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Aug 14 07:44:50 PDT 2016


This is an approach to n x n thread message passing.  The idea is that 
each thread should be able to pass messages to any other thread.  The 
only alternative I've come up with involves the main thread handling 
each message.  Is that a better approach?  Is there a better way to pass 
lists of Tids?

import    std.concurrency;
import    std.stdio;

import    core.thread;

shared    Tid[3]    tidList;

struct    Start    {    int    dummy    =    0;    }
struct    Msg    {    int    orig;    int    dest;    }
struct    Done    {    int    dummy    =    0;    }

void    worker (int ndx)
{
     writeln    ("worker ", ndx, " spawned");
     {  auto    msg    =    receiveOnly!(Start)();
         writeln    ("worker ", ndx, " started");
     }
     Tid[]    tids;
     foreach    (t; tidList)    {    tids    ~=    cast(Tid)t;    }
     for    (int i = 0;    i < 3;    i++)
     {   if    (i != ndx)
         {  Msg msg    =    Msg(ndx, i);
             send (tids[i], msg);
         }
     }
     writeln    ("worker ", ndx, " got tidList");
     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);
         tidList[i]    =    cast(shared Tid)tid;
     }
     foreach (i; 0 .. 3)    {    send (cast(Tid)tidList[i], start);    }
     Thread.sleep (1000.msecs);
     foreach (i; 0 .. 3)    {    send (cast(Tid)tidList[i], done);    }
     Thread.sleep (1000.msecs);
     writeln ("main is done");
}



More information about the Digitalmars-d-learn mailing list