On Monday, 29 July 2013 at 15:28:45 UTC, lindenk wrote:
Hello!
This is partially a general question as I don't know what this is called or if it exists. Say for example I want to do something like the following -

import std.concurrency;

void main()
{
    void foo() {
        try
        {
            while(true)
            {
                 do_some_blocking_function();
            }
        } catch(GotAMessage msg){}

        // clean up
    };

    tid = spawn(&foo, thisTid);

    // do stuff / wait for some condition

    send(tid, "STAHP!");
}

One solution I've used in the past is setting a timeout for the blocking function then polling to see if the thread should exit. The disadvantage is it causes extra, unnecessary checking and has a delay before it gets the message and exits.

This is a fairly simple example but the idea should be the same, is there a way to pass a message or signal to a thread to cause it to branch to some other location?

import std.concurrency;
import core.time;

void foo(Tid parent) {
    bool run = true;
    while(run)
    {
         //do_some_blocking_function();
         receiveTimeout(dur!"msecs"(0),
             (string s){if(s == "STAHP!") run = false;}
         );
    }

    // clean up
    send(parent, "done");
}


void main()
{
    auto tid = spawn(&foo, thisTid);

    // do stuff / wait for some condition

    send(tid, "STAHP!");
    auto msg = receiveOnly!(string)();
    assert(msg == "done");
}

Reply via email to