Sending an immutable object to a thread

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Jul 19 01:30:09 PDT 2015


It is a pitty that although Variant is the default message type in 
concurrency, it still has issues:

 
https://issues.dlang.org/buglist.cgi?quicksearch=variant%20concurrency&list_id=202195

It looks like passing a pointer to an immutable(Message) works as well:

import std.stdio;
import std.concurrency;

class Message
{
     int i;

     this(int i) immutable
     {
         this.i = i;
     }
}

int do_something_with(immutable(Message) msg)
{
     writefln("msg.i is %s", msg.i);
     return 0;
}

void threadFunc()
{
     receive((Tid cli, immutable(Message) *msg) {
             int retCode = do_something_with(*msg);
             send(cli, retCode);
         });

     ownerTid.send(42);
}


void main()
{
     auto msg = new immutable(Message)(100);

     Tid tid = spawn(&threadFunc);
     send(tid, thisTid(), &msg);    // <-- POINTER
     receiveOnly!int();
}

Ali



More information about the Digitalmars-d-learn mailing list