Acme-Parataxis

 view release on metacpan or  search on metacpan

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

=pod

=encoding utf8

=head1 NAME

Acme::Parataxis::Semaphore - Counting Semaphore for Fiber Synchronization and Resource Pools

=head1 SYNOPSIS

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

    async {
        # Limit concurrency to 3 simultaneous fibers:
        my $pool = Acme::Parataxis::Semaphore->new( count => 3 );

        my @workers = map {
            my $id = $_;
            fiber {
                $pool->down;    # acquire permit (parks if count == 0)
                say "Worker $id acquired permit";
                await_sleep(50);
                $pool->up;      # release permit back to pool
            };
        } 1 .. 6;

        $_->await for @workers;
    };

=head1 DESCRIPTION

A counting semaphore manages a pool of abstract permits. Fibers request permits via C<down> (parking if none are
available) and return permits via C<up>.

Semaphores have no concept of thread or fiber ownership: one fiber can call C<down> while an entirely different fiber
calls C<up>, and permits can be added before any fiber requests them.

Waiters park cooperatively in FIFO order without polling. Parked waits integrate with Parataxis structured concurrency:
they can be interrupted cleanly via L<with_timeout|Acme::Parataxis/with_timeout> or cancellation tokens, and
interrupted fibers automatically unregister from the wait queue without consuming leaked permits.

C<Acme::Parataxis::Semaphore> is a foundational building block for the rest of the distribution: channels use two
internal semaphores for read and write queues, rate limiters use one as a token bucket, and mutexes wrap a semaphore
with strict owner tracking.

=head1 METHODS

=head2 C<new( [ count =E<gt> $n = 1 ] )>

    my $sem = Acme::Parataxis::Semaphore->new;             # default 1 permit
    my $sem = Acme::Parataxis::Semaphore->new( count => 5 );

Constructs a new semaphore with C<$n> initial permits. Keyword-only.

=head2 C<down( [$reason = 'Semaphore down'] )>

    $sem->down;

Decrements the permit count by 1. If the permit count is zero or negative, the calling fiber parks until a permit is
returned via C<up()> or C<adjust()>. Returns true.



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