Correct way to spawn many and stoping when one finishes ?
Steven Schveighoffer via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Tue Apr 12 05:12:19 PDT 2016
On 4/10/16 4:59 AM, klimp wrote:
> On Sunday, 10 April 2016 at 07:48:51 UTC, klimp wrote:
>> Is this corrrect ? Each task searches for the same thing so when once
>> has found the others don't need to run anymore. It looks a bit strange
>> not to stop those who havent find the thing:
>
> Actually I have to kill the other tasks, in this slightly modified try:
>
> import std.concurrency, core.thread, std.random, std.stdio;
>
> void task()
> {
> size_t i;
> while (true)
> {
> Thread.sleep(dur!"nsecs"(rndGen.front / 50));
> ++i;
> rndGen.popFront;
> if (i == 100)
> {
> send(ownerTid, thisTid, true);
> writeln("thisT gonna write globals: ", thisTid);
> if (receiveOnly!bool)
> writeln("thisT writes globals: ", thisTid);
> send(ownerTid, true);
> break;
> }
> }
>
> }
>
> void main()
> {
> Tid t0 = spawn(&task);
> Tid t1 = spawn(&task);
>
> auto t = receiveOnly!(Tid, bool);
> if (t[0] == t1) send(t0, false);
> if (t[0] == t0) send(t1, false);
> if (t[1])
> {
> send(t[0], true);
> receiveOnly!bool;
> return;
> }
> }
>
> I got as output:
>
>> thisT gonna write globals: Tid(7ff8d3035100)
>> thisT writes globals: Tid(7ff8d3035100)
>> thisT gonna write globals: Tid(7ff8d3035400)
>
> but I don't want the other spawned thread to continue until the end.
>
> I should only get:
>
>> thisT gonna write globals: Tid(7ff8d3035100)
>> thisT writes globals: Tid(7ff8d3035100)
>
> How can I kill a Tid ?
Short answer: don't.
This is kind of why there isn't a handy function to do so.
If you kill a thread, there is no telling what state it is in, what
locks it has held, etc.
The best (and really only) way to manage threads is through a loop that
checks periodically whether it should quit.
-Steve
More information about the Digitalmars-d-learn
mailing list