How to implement Canceleable spawn() from parent

Simen Kjærås simen.kjaras at gmail.com
Tue Jun 30 12:48:32 UTC 2020


On Tuesday, 30 June 2020 at 08:15:54 UTC, aberba wrote:
> On Tuesday, 30 June 2020 at 00:33:41 UTC, Ali Çehreli wrote:
>> On 6/29/20 4:34 PM, aberba wrote:
>>
>> > So with this, without the Thread.sleep() to block main from
>> exiting, the
>> > spawned thread  will terminate immediately.
>>
>> You can call core.thread.thread_joinAll at the end of main.
> So I tried that initially but my (){ writeln(...) } wasn't 
> printing anything in console. Could that be related to stdout 
> buffering? The program kept running though.

Seems weird. This works great on my machine:


import core.time : Duration, msecs;
import core.thread : Thread, thread_joinAll;
import std.concurrency : spawn, Tid, send, receiveTimeout;
import std.stdio : writeln;

private struct IntervalStop {}

Tid setInterval(Duration dur, void function() fn) {
     return spawn((Duration d, void function() f){
         while (!receiveTimeout(d, (IntervalStop s){})) {
             f();
         }
     }, dur, fn);
}

void stopInterval(Tid tid) {
     tid.send(IntervalStop());
}

void main() {
     auto a = setInterval(1000.msecs, (){ writeln("Hello from 
spawned thread A"); });
     // Stop it before it happens
     stopInterval(a);
     Thread.sleep(2000.msecs);

     auto b = setInterval(1000.msecs, (){ writeln("Hello from 
spawned thread B"); });
     // Let this one run a little
     Thread.sleep(2500.msecs);
     stopInterval(b);

     auto c = setInterval(1000.msecs, (){ writeln("Hello from 
spawned thread C"); });
     // Sending the wrong message doesn't make it happen or stop 
prematurely
     c.send("Stop this at once!");
     Thread.sleep(2500.msecs);
     stopInterval(c);

     thread_joinAll();
}

So I guess the error is elsewhere, but I'm not sure where and how.

--
   Simen


More information about the Digitalmars-d-learn mailing list