=begin pod

=TITLE class Thread

=SUBTITLE Concurrent execution of code (low-level)

    class Thread { ... }

A L<thread|https://en.wikipedia.org/wiki/Thread_%28computing%29> is a sequence
of instructions that can (potentially) run in parallel to others. Class
C<Thread> provides a bit of abstraction over threads provided by the
underlying virtual machines (which in turn might or might not be operating
system threads).

Since threads are fairly low-level, most applications should use other
primitives, like L<start|/type/Promise#method start>, which also runs in
parallel and returns a L<Promise|/type/Promise>.

=begin code
use v6;
my @threads = (^10).map: {
    Thread.start(
        name => "Sleepsorter $_",
        sub {
            my $rand = (^10).pick;
            sleep $rand;
            say $rand;
        },
    );
}

.finish for @threads;
=end code

The current thread is available in the dynamic variable C<$*THREAD>.

=head1 Methods

=head2 method new

    method new(:&code!, Bool :$app_lifetime = False, Str $name = '<anon>') returns Thread:D

Creates and returns a new C<Thread>, without starting it yet. C<&code> is the
code that will be run in a separate thread.

C<$name> is a user-specified string that identifies the thread.

If C<$app_lifetime> is set to C<True>, then the thread is killed when the main
thread of the process terminates. If set to C<False>, the process will only
terminate when the thread has finished.

=head2 method start

    method start(Thread:U: &code, Bool :$app_lifetime = False, Str $name = '<anon>') returns Thread:D 
Creates, runs and returns a new C<Thread>. Note that it can (and often does)
return before the thread's code has finished running.

=head2 method run

    method run(Thread:D:)

Runs the thread, and returns the invocant. It is an error to run a thread that
has already been started.

=head2 method id

    method id(Thread:D:) returns Int:D

Returns a numeric, unique thread identifier.

=head2 method finish

    method finish(Thread:D)

Waits for the thread to finish. This is called I<join> in other programming
systems.

=head2 method yield

    method yield(Thread:U)

Tells the scheduler to prefer another thread for now.

    Thread.yield;

=end pod
