How to kill whole application if child thread raises an exception?

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Oct 27 06:37:29 PDT 2016


On 10/26/16 4:42 AM, dm wrote:
> Hi. I tried code below:
>
> import std.concurrency;
> import std.stdio;
>
> void func()
> {
>     throw new Exception("I'm an exception");
> }
>
> void main()
> {
>     auto tID = spawn(&func);
>     foreach(line; stdin.byLine)
>         send(tID, "");
> }
>
> I expect my application will die immediatly, but main thread still
> running and I don't see any errors.
> I want to kill all my threads if it is unhandled exception.
> How can I do that?

Hm... what about:

import std.traits: Parameters;

auto mySpawn(F)(F func, Parameters!F params)
{
     static auto callIt(F func, Parameters!F params)
     {
         try
         {
             return func(params);
         }
         catch(Throwable t)
         {
             // print the exception/error, e.g.:
             import std.writeln;
             writeln(e.toString());
             // terminate program
             import core.stdc.stdlib : exit;
             exit(1);
         }
     }

     return spawn(&callIt, func, params);
}

void main()
{
     auto tID = mySpawn(&func);
     ...
}

-Steve


More information about the Digitalmars-d-learn mailing list