ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/Coro/Coro/Semaphore.pm
Revision: 1.7
Committed: Thu Jul 19 02:45:09 2001 UTC (22 years, 10 months ago) by root
Branch: MAIN
Changes since 1.6: +1 -1 lines
Log Message:
*** empty log message ***

File Contents

# Content
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 [initial value];
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 ();
26
27 $VERSION = 0.08;
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
36 sub new {
37 bless [defined $_[1] ? $_[1] : 1], $_[0];
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
46
47 sub down {
48 my $self = shift;
49 while ($self->[0] <= 0) {
50 push @{$self->[1]}, $Coro::current;
51 Coro::schedule;
52 }
53 --$self->[0];
54 }
55
56 =item $sem->up
57
58 Unlock the semaphore again.
59
60 =cut
61
62 sub up {
63 my $self = shift;
64 if (++$self->[0] > 0) {
65 (shift @{$self->[1]})->ready if @{$self->[1]};
66 }
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
75
76 sub try {
77 my $self = shift;
78 if ($self->[0] > 0) {
79 --$self->[0];
80 return 1;
81 } else {
82 return 0;
83 }
84 }
85
86 1;
87
88 =back
89
90 =head1 AUTHOR
91
92 Marc Lehmann <pcg@goof.com>
93 http://www.goof.com/pcg/marc/
94
95 =cut
96