Course of Raku / Functional, concurrent, reactive, and web programming / Concurrent programming / Threads
Joining threads
To wait for a thread to complete, call .finish on it
(also spelled .join). The main program pauses there until
the thread is done:
my $t = Thread.start({ say 'in the thread' });
$t.finish;
say 'done';This prints:
in the thread
doneBecause .finish waits, the thread’s message is
guaranteed to appear before done. Without the
.finish, the order would be unpredictable, and the program
might even end before the thread had a chance to print.
When you start several threads, you join each one to be sure they have all completed:
my $a = Thread.start({ 1 + 1 });
my $b = Thread.start({ 2 + 2 });
$a.finish;
$b.finish;
say 'both finished';The two threads run concurrently, and joining both before the final
say guarantees that both finished is printed
only once they are truly done. Joining is how you bring concurrent work
back together into a predictable point in your program.
Course navigation
← Quiz — Threads | Run in a thread →
💪 Or jump directly to
the exercises in this section.