Acme-Parataxis
view release on metacpan or search on metacpan
lib/Acme/Parataxis/Sync/Once.pod view on Meta::CPAN
=pod
=encoding utf8
=head1 NAME
Acme::Parataxis::Sync::Once - Run an Initialization Action Exactly Once Across Concurrent Fibers
=head1 SYNOPSIS
use v5.40;
use Acme::Parataxis qw[async fiber];
use Acme::Parataxis::Sync::Once;
my $initializer = Acme::Parataxis::Sync::Once->new;
my $connection;
async {
my @workers = map {
my $id = $_;
fiber {
# First fiber executes the block; subsequent fibers park until done:
$initializer->do( sub {
say "Worker $id initializing shared database connection...";
$connection = connect_to_db();
} );
say "Worker $id proceeding with connection: $connection";
};
} 1 .. 4;
$_->await for @workers;
};
=head1 DESCRIPTION
C<Acme::Parataxis::Sync::Once> coordinates lazy, one-time initializations across concurrent fibers. The first fiber to
call C<do> executes the provided action; all other concurrent callers park until the action completes and then proceed.
Once the action has completedâwhether it returned cleanly, died, or was interruptedâthe initializer is marked done.
Subsequent calls to C<do> return immediately without re-executing the action.
=head2 Result Asymmetry
A key design property: B<only the fiber that actually executes the action receives its return value>. Concurrent
waiters and later callers return C<undef>. For this reason, shared initializers should assign their results to an
enclosing lexical variable (as shown in the SYNOPSIS) rather than relying on the return value of C<do()>.
=head1 METHODS
=head2 C<new( )>
my $once = Acme::Parataxis::Sync::Once->new;
Constructs a new, unexecuted C<Once> instance.
=head2 C<do( sub { ... } )>
my $res = $once->do( sub { initialize() } );
Executes the code reference if it has never run before:
=over
( run in 1.505 second using v1.01-cache-2.11-cpan-234fa220139 )