In Control flow§
See primary documentation in context for start
The simplest way to run a statement or block asynchronously is by writing start
before it:
startsay "working";# working, done
Note that you need a space between the start
and the block. In the example above, the start
block is in sink context since it's not assigned to a variable. From version 6.d, these sunk blocks have an exception handler attached:
startsay "working";sleep 10;
This code will print Unhandled exception in code scheduled on thread 4 We're dead
in version 6.d, while it will simply get out after waiting for 10 seconds in version 6.c.
The start {...}
immediately returns a Promise
that can be safely ignored if you are not interested in the result of the block. If you are interested in the final value of the block, you can call the .result
method on the returned promise. So:
my = start# ... do other stuffsay "The result is $promise.result()";
If the code inside the block has not finished, the call to .result
will wait until it is done.
A start
used on a bare statement is useful when the only thing to do asynchronously is a subroutine or method:
sub get42my = start get42;say .result; # OUTPUT: «42»
Note that start code does not have access to the special variables $!
and $/
of its outer block, but receives new ones, so every asynchronous task has its per-task state.
Thus, try
expressions and regex matches executed in the asynchronous task have their per-task state.
'a' ~~ /a/; # $/ is set to 「a」try die; # $! is defined now with an anonymous AdHoc exception# as a code blockawait start ; # OUTPUT: «Nil»await start ; # OUTPUT: «Nil»# as a single statementawait start $!.say; # OUTPUT: «Nil»await start $/.say; # OUTPUT: «Nil»