Acme-Parataxis

 view release on metacpan or  search on metacpan

lib/Acme/Parataxis/Sync/RwLock.pod  view on Meta::CPAN

=pod

=encoding utf8

=head1 NAME

Acme::Parataxis::Sync::RwLock - Writer-Preferring Reader-Writer Lock for Fibers

=head1 SYNOPSIS

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

    my $rwlock = Acme::Parataxis::Sync::RwLock->new;
    my %cache  = ( a => 1, b => 2 );

    async {
        # Concurrent readers share the lock simultaneously:
        my @readers = map {
            my $id = $_;
            fiber {
                my $guard = $rwlock->read_guard;
                say "Reader $id active; concurrent read holds: " . $rwlock->readers;
                await_sleep(20);
            };
        } 1 .. 3;

        # Writer claims exclusive access; queues behind current readers
        # but blocks all subsequent readers from jumping ahead:
        my $writer = fiber {
            await_sleep(5);
            my $guard = $rwlock->write_guard;
            say "Writer active (exclusive); updating cache...";
            $cache{c} = 3;
        };

        $_->await for @readers, $writer;
        say "Cache updated safely: " . keys(%cache) . " items";
    };

=head1 DESCRIPTION

C<Acme::Parataxis::Sync::RwLock> provides a shared-reader, exclusive-writer lock for coordinating fibers. Multiple
fibers may acquire concurrent read holds, but a write lock is strictly exclusive: no other reader or writer may enter
while a write hold is active.

=head2 Writer Preference

In a naive reader-writer lock, a continuous stream of readers can starve a queued writer indefinitely.
C<Acme::Parataxis::Sync::RwLock> enforces B<writer preference>:

=over

=item *

The moment a writer requests a lock (calling C<write_lock> or C<write_guard>), any subsequent reader arriving at the
lock is placed in the wait queue behind that writer.

=item *

Existing active readers are allowed to drain naturally. Once the last reader finishes, the queued writer is granted the
lock immediately.



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