Acme-Parataxis

 view release on metacpan or  search on metacpan

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

=pod

=encoding utf8

=head1 NAME

Acme::Parataxis::Blocking - Run CPU-Bound Perl Closures on Background Interpreters or Forked Children

=head1 SYNOPSIS

    use v5.40;
    use Acme::Parataxis qw[async fiber await_sleep];
    use Acme::Parataxis::Blocking qw[spawn_blocking spawn_blocking_fork kill_blocking_fork];

    async {
        # Offload CPU-heavy computation to a background thread interpreter:
        my $future = spawn_blocking( sub ($data) {
            return heavy_cpu_digest($data);
        }, $payload );

        # Other fibers continue running smoothly while the background thread computes
        fiber {
            await_sleep(10);
            say 'Cooperative fibers are still running!';
        };

        my $result = $future->await;
        say "Digest: $result";
    };

=head1 DESCRIPTION

The C<Acme::Parataxis> native C worker pool handles blocking I/O and sleeps, but it cannot run arbitrary Perl code
without blocking the main interpreter. C<Acme::Parataxis::Blocking> offloads heavy, CPU-bound Perl closures to separate
execution contexts so your cooperative fibers never drop frames or stall.

Two backends are provided:

=over

=item *

B<C<spawn_blocking>>: Runs the closure on an isolated background Perl interpreter using native threads
(C<threads-E<gt>create>). Requires a Perl built with ithreads (C<useithreads>). Thread dependencies (C<threads>,
C<threads::shared>, C<Thread::Queue>) are loaded lazily on the first invocation.

=item *

B<C<spawn_blocking_fork>>: Runs the closure in a forked child process, marshaling arguments and results over a pipe
using L<Storable>. Works on non-threaded Perls (POSIX platforms where C<d_fork> is defined).

=back

Both functions return an L<Acme::Parataxis::Future> that can be awaited, combined with C<wait_all>/C<wait_any>, or
bounded with C<with_timeout>.

=head1 FUNCTIONS

=head2 C<spawn_blocking( $code, [@args] )>

    my $future = spawn_blocking( sub ($x, $y) {
        return $x ** $y;
    }, 2, 64 );



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