Acme-Parataxis

 view release on metacpan or  search on metacpan

lib/Acme/Parataxis/CancellationToken.pod  view on Meta::CPAN

=pod

=encoding utf8

=head1 NAME

Acme::Parataxis::CancellationToken - Cooperative Wait Interruption and Cancellation Tokens

=head1 SYNOPSIS

    use v5.40;
    use Acme::Parataxis qw[async fiber await_sleep with_timeout];
    use Acme::Parataxis::CancellationToken;

    my $cancel = Acme::Parataxis::CancellationToken->new;    # nobody has cancelled it yet

    async {
        fiber {
            await_sleep(50);
            $cancel->cancel;                                  # ... until this fiber says so
        };

        my $done = eval { with_timeout( 10_000, $cancel, sub { await_sleep(10_000) } ) };
        say $done // "gave up: $@";    # gave up: The operation was cancelled at await_sleep (...)
    };

=head1 DESCRIPTION

A token is a flag paired with a registry of fiber IDs. A fiber that wants to be interruptible registers itself on the
token; whoever wants that work stopped calls C<cancel>, and the wait each registered fiber is sitting in throws an
exception (L<Acme::Parataxis::Error::Cancelled> by default) instead of returning.

Cancelling does not kill anything violently. It marks the registered fibers and wakes them. The exception is thrown at
the re-entry of the specific wait they were parked in, so each one unwinds from its own execution point: C<eval>
guards, C<defer>s, C<finally> blocks, and object destructors all run on the way out. An interrupted wait also
unregisters itself from whatever primitive it was waiting on, so the fiber is not left attached to a channel, future,
or semaphore that could wake it again later.

You rarely have to build a token manually:

=over

=item * L<with_cancel|Acme::Parataxis/with_cancel> creates one and hands it to its block.

=item * L<with_timeout|Acme::Parataxis/with_timeout> arms one per deadline.

=item * A L<nursery|Acme::Parataxis/nursery> owns one to cancel siblings on failure.

=item * L<run|Acme::Parataxis/run> takes one as C<on_shutdown>.

=back

See L</"Tokens You Get for Free">. Instantiate your own when the work is not yours to wrap in a block, or when multiple
independent fibers need the authority to call off shared work.

=head1 METHODS

=head2 C<new( [ kind =E<gt> 'cancel' ] )>

    my $cancel   = Acme::Parataxis::CancellationToken->new;
    my $deadline = Acme::Parataxis::CancellationToken->new( kind => 'timeout' );

Constructs a fresh, uncancelled token.



( run in 1.145 second using v1.01-cache-2.11-cpan-234fa220139 )