--- Coro/Coro/Semaphore.pm 2001/09/24 01:36:20 1.21 +++ Coro/Coro/Semaphore.pm 2003/11/05 20:02:46 1.36 @@ -33,11 +33,11 @@ package Coro::Semaphore; -no warnings qw(uninitialized); +BEGIN { eval { require warnings } && warnings->unimport ("uninitialized") } use Coro (); -$VERSION = 0.5; +$VERSION = 0.8; =item new [inital count] @@ -57,6 +57,11 @@ Decrement the counter, therefore "locking" the semaphore. This method waits until the semaphore is available if the counter is zero. +=item $status = $sem->timed_down($timeout) + +Like C, but returns false if semaphore couldn't be acquired within +$timeout seconds, otherwise true. + =cut sub down { @@ -67,6 +72,29 @@ --$_[0][0]; } +sub timed_down { + require Coro::Timer; + my $timeout = Coro::Timer::timeout($_[1]); + + while ($_[0][0] <= 0) { + push @{$_[0][1]}, $Coro::current; + Coro::schedule; + if ($timeout) { + # ugly as hell. slow, too, btw! + for (0..$#{$_[0][1]}) { + if ($_[0][1][$_] == $Coro::current) { + splice @{$_[0][1]}, $_, 1; + return; + } + } + die; + } + } + + --$_[0][0]; + return 1; +} + =item $sem->up Unlock the semaphore again. @@ -111,16 +139,27 @@ This method calls C and then creates a guard object. When the guard object is destroyed it automatically calls C. +=item $guard = $sem->timed_guard($timeout) + +Like C, but returns undef if semaphore couldn't be acquired within +$timeout seconds, otherwise the guard object. + =cut sub guard { &down; # double indirection because bless works on the referenced # object, not (only) on the reference itself. - bless \\$_[0], Coro::Semaphore::Guard::; + bless \\$_[0], Coro::Semaphore::guard::; +} + +sub timed_guard { + &timed_down + ? bless \\$_[0], Coro::Semaphore::guard:: + : (); } -sub Coro::Semaphore::Guard::DESTROY { +sub Coro::Semaphore::guard::DESTROY { &up(${${$_[0]}}); }