Acme-Parataxis
view release on metacpan or search on metacpan
lib/Acme/Parataxis/TVar.pod view on Meta::CPAN
=pod
=encoding utf8
=head1 NAME
Acme::Parataxis::TVar - Software Transactional Memory (STM) with Versioned Cells
=head1 SYNOPSIS
use v5.40;
use Acme::Parataxis qw[async fiber await_sleep atomically retry];
use Acme::Parataxis::TVar;
my $account = Acme::Parataxis::TVar->new( value => 5 );
async {
# Consumer: waits for sufficient balance using retry
my $taker = fiber {
atomically {
my $have = $account->get;
retry if $have < 10; # balance insufficient: park until modified
$account->set( $have - 10 );
return 'withdrew 10';
};
};
await_sleep(10);
say "Taker parked; waiters: " . $account->waiters; # 1
# Producer: deposit funds to satisfy the condition
atomically {
$account->set( $account->get + 20 );
};
say $taker->await . ", balance: " . $account->value; # withdrew 10, balance: 15
};
=head1 DESCRIPTION
A C<TVar> (Transactional Variable) is a mutable cell paired with a version counter. Rather than reading and writing
cells directly, operations are wrapped in an C<atomically> block and accessed through C<get> and C<set>. Writes remain
staged and isolated until the outermost transaction commits; at commit time, all writes land atomically as a single
unit, or none do.
This provides lock-free composability:
=over
=item *
B<Zero interleaving>: Two fibers performing multi-variable transfers cannot observe half-completed states. Either the
entire transaction commits, or it conflicts and restarts.
=item *
B<Automatic conflict resolution>: If another fiber commits changes to any TVar read by your transaction before your
transaction commits, your staged writes are discarded and your block is automatically re-run from the top.
=item *
B<Conditional waiting without polling>: Calling C<retry> aborts the current transaction and parks the calling fiber
until at least one of the TVars in its read set is committed by another fiber, whereupon the block re-runs
( run in 0.844 second using v1.01-cache-2.11-cpan-234fa220139 )