1 |
root |
1.1 |
=head1 NAME |
2 |
|
|
|
3 |
|
|
Coro::Semaphore - non-binary semaphores |
4 |
|
|
|
5 |
|
|
=head1 SYNOPSIS |
6 |
|
|
|
7 |
|
|
use Coro::Semaphore; |
8 |
|
|
|
9 |
|
|
$sig = new Coro::Semaphore [init]; |
10 |
|
|
|
11 |
|
|
$sig->down; # wait for signal |
12 |
|
|
|
13 |
|
|
# ... some other "thread" |
14 |
|
|
|
15 |
|
|
$sig->up; |
16 |
|
|
|
17 |
|
|
=head1 DESCRIPTION |
18 |
|
|
|
19 |
|
|
=over 4 |
20 |
|
|
|
21 |
|
|
=cut |
22 |
|
|
|
23 |
|
|
package Coro::Semaphore; |
24 |
|
|
|
25 |
|
|
use Coro::Process (); |
26 |
|
|
|
27 |
|
|
$VERSION = 0.01; |
28 |
|
|
|
29 |
|
|
sub new { |
30 |
root |
1.2 |
bless [defined $_[1] ? $_[1] : 1], $_[0]; |
31 |
root |
1.1 |
} |
32 |
|
|
|
33 |
|
|
sub down { |
34 |
|
|
my $self = shift; |
35 |
|
|
while ($self->[0] <= 0) { |
36 |
|
|
push @{$self->[1]}, $Coro::current; |
37 |
|
|
Coro::Process::schedule; |
38 |
|
|
} |
39 |
|
|
--$self->[0]; |
40 |
|
|
} |
41 |
|
|
|
42 |
|
|
sub up { |
43 |
|
|
my $self = shift; |
44 |
root |
1.2 |
if (++$self->[0] > 0) { |
45 |
root |
1.1 |
(shift @{$self->[1]})->ready if @{$self->[1]}; |
46 |
|
|
} |
47 |
|
|
} |
48 |
|
|
|
49 |
|
|
sub try { |
50 |
|
|
my $self = shift; |
51 |
|
|
if ($self->[0] > 0) { |
52 |
|
|
--$self->[0]; |
53 |
|
|
return 1; |
54 |
|
|
} else { |
55 |
|
|
return 0; |
56 |
|
|
} |
57 |
|
|
} |
58 |
|
|
|
59 |
|
|
1; |
60 |
|
|
|
61 |
|
|
=back |
62 |
|
|
|
63 |
|
|
=head1 AUTHOR |
64 |
|
|
|
65 |
|
|
Marc Lehmann <pcg@goof.com> |
66 |
|
|
http://www.goof.com/pcg/marc/ |
67 |
|
|
|
68 |
|
|
=cut |
69 |
|
|
|