… | |
… | |
4 | |
4 | |
5 | =head1 SYNOPSIS |
5 | =head1 SYNOPSIS |
6 | |
6 | |
7 | use Coro::Semaphore; |
7 | use Coro::Semaphore; |
8 | |
8 | |
9 | $sig = new Coro::Semaphore [init]; |
9 | $sig = new Coro::Semaphore [initial value]; |
10 | |
10 | |
11 | $sig->down; # wait for signal |
11 | $sig->down; # wait for signal |
12 | |
12 | |
13 | # ... some other "thread" |
13 | # ... some other "thread" |
14 | |
14 | |
… | |
… | |
24 | |
24 | |
25 | use Coro::Process (); |
25 | use Coro::Process (); |
26 | |
26 | |
27 | $VERSION = 0.01; |
27 | $VERSION = 0.01; |
28 | |
28 | |
|
|
29 | =item new [inital count, default zero] |
|
|
30 | |
|
|
31 | Creates a new sempahore object with the given initial lock count. The |
|
|
32 | default lock count is 1, which means it is unlocked by default. |
|
|
33 | |
|
|
34 | =cut |
|
|
35 | |
29 | sub new { |
36 | sub new { |
30 | bless [defined $_[1] ? $_[1] : 1], $_[0]; |
37 | bless [defined $_[1] ? $_[1] : 1], $_[0]; |
31 | } |
38 | } |
|
|
39 | |
|
|
40 | =item $sem->down |
|
|
41 | |
|
|
42 | Decrement the counter, therefore "locking" the semaphore. This method |
|
|
43 | waits until the semaphore is available if the counter is zero. |
|
|
44 | |
|
|
45 | =cut |
32 | |
46 | |
33 | sub down { |
47 | sub down { |
34 | my $self = shift; |
48 | my $self = shift; |
35 | while ($self->[0] <= 0) { |
49 | while ($self->[0] <= 0) { |
36 | push @{$self->[1]}, $Coro::current; |
50 | push @{$self->[1]}, $Coro::current; |
37 | Coro::Process::schedule; |
51 | Coro::Process::schedule; |
38 | } |
52 | } |
39 | --$self->[0]; |
53 | --$self->[0]; |
40 | } |
54 | } |
41 | |
55 | |
|
|
56 | =item $sem->up |
|
|
57 | |
|
|
58 | Unlock the semaphore again. |
|
|
59 | |
|
|
60 | =cut |
|
|
61 | |
42 | sub up { |
62 | sub up { |
43 | my $self = shift; |
63 | my $self = shift; |
44 | if (++$self->[0] > 0) { |
64 | if (++$self->[0] > 0) { |
45 | (shift @{$self->[1]})->ready if @{$self->[1]}; |
65 | (shift @{$self->[1]})->ready if @{$self->[1]}; |
46 | } |
66 | } |
47 | } |
67 | } |
|
|
68 | |
|
|
69 | =item $sem->try |
|
|
70 | |
|
|
71 | Try to C<down> the semaphore. Returns true when this was possible, |
|
|
72 | otherwise return false and leave the semaphore unchanged. |
|
|
73 | |
|
|
74 | =cut |
48 | |
75 | |
49 | sub try { |
76 | sub try { |
50 | my $self = shift; |
77 | my $self = shift; |
51 | if ($self->[0] > 0) { |
78 | if ($self->[0] > 0) { |
52 | --$self->[0]; |
79 | --$self->[0]; |