--- Coro/Coro/Semaphore.pm 2001/07/17 15:42:28 1.6 +++ Coro/Coro/Semaphore.pm 2001/11/06 20:34:11 1.23 @@ -16,20 +16,35 @@ =head1 DESCRIPTION +This module implements counting semaphores. You can initialize a mutex +with any level of parallel users, that is, you can intialize a sempahore +that can be Ced more than once until it blocks. There is no owner +associated with semaphores, so one coroutine can C it while another +can C it. + +Counting semaphores are typically used to coordinate access to +resources, with the semaphore count initialized to the number of free +resources. Coroutines then increment the count when resources are added +and decrement the count when resources are removed. + =over 4 =cut package Coro::Semaphore; +no warnings qw(uninitialized); + use Coro (); -$VERSION = 0.07; +$VERSION = 0.52; -=item new [inital count, default zero] +=item new [inital count] Creates a new sempahore object with the given initial lock count. The -default lock count is 1, which means it is unlocked by default. +default lock count is 1, which means it is unlocked by default. Zero (or +negative values) are also allowed, in which case the semaphore is locked +by default. =cut @@ -45,12 +60,11 @@ =cut sub down { - my $self = shift; - while ($self->[0] <= 0) { - push @{$self->[1]}, $Coro::current; + while ($_[0][0] <= 0) { + push @{$_[0][1]}, $Coro::current; Coro::schedule; } - --$self->[0]; + --$_[0][0]; } =item $sem->up @@ -60,9 +74,8 @@ =cut sub up { - my $self = shift; - if (++$self->[0] > 0) { - (shift @{$self->[1]})->ready if @{$self->[1]}; + if (++$_[0][0] > 0) { + (shift @{$_[0][1]})->ready if @{$_[0][1]}; } } @@ -74,15 +87,43 @@ =cut sub try { - my $self = shift; - if ($self->[0] > 0) { - --$self->[0]; + if ($_[0][0] > 0) { + --$_[0][0]; return 1; } else { return 0; } } +=item $sem->waiters + +In scalar context, returns the number of coroutines waiting for this +semaphore. + +=cut + +sub waiters { + @{$_[0][1]}; +} + +=item $guard = $sem->guard + +This method calls C and then creates a guard object. When the guard +object is destroyed it automatically calls C. + +=cut + +sub guard { + &down; + # double indirection because bless works on the referenced + # object, not (only) on the reference itself. + bless \\$_[0], Coro::Semaphore::Guard::; +} + +sub Coro::Semaphore::Guard::DESTROY { + &up(${${$_[0]}}); +} + 1; =back