Commit | Line | Data |
d21067e0 |
1 | package Thread::Semaphore; |
2 | use Thread qw(cond_wait cond_broadcast); |
3 | |
d516a115 |
4 | =head1 NAME |
5 | |
6 | Thread::Semaphore - thread-safe semaphores |
7 | |
8 | =head1 SYNOPSIS |
9 | |
10 | use Thread::Semaphore; |
11 | my $s = new Thread::Semaphore; |
12 | $s->up; # Also known as the semaphore V -operation. |
13 | # The guarded section is here |
14 | $s->down; # Also known as the semaphore P -operation. |
15 | |
16 | # The default semaphore value is 1. |
17 | my $s = new Thread::Semaphore($initial_value); |
18 | $s->up($up_value); |
19 | $s->down($up_value); |
20 | |
5d582a37 |
21 | =head1 DESCRIPTION |
22 | |
23 | Semaphores provide a mechanism to regulate access to resources. Semaphores, |
24 | unlike locks, aren't tied to particular scalars, and so may be used to |
25 | control access to anything you care to use them for. |
26 | |
27 | Semaphores don't limit their values to zero or one, so they can be used to |
28 | control access to some resource that may have more than one of. (For |
29 | example, filehandles) Increment and decrement amounts aren't fixed at one |
30 | either, so threads can reserve or return multiple resources at once. |
31 | |
32 | =head1 FUNCTIONS AND METHODS |
33 | |
34 | =over 8 |
35 | |
36 | =item new |
37 | |
38 | =item new NUMBER |
39 | |
40 | C<new> creates a new semaphore, and initializes its count to the passed |
41 | number. If no number is passed, the semaphore's count is set to one. |
42 | |
43 | =item down |
44 | |
45 | =item down NUMBER |
46 | |
47 | The C<down> method decreases the semaphore's count by the specified number, |
48 | or one if no number has been specified. If the semaphore's count would drop |
49 | below zero, this method will block until such time that the semaphore's |
50 | count is equal to or larger than the amount you're C<down>ing the |
51 | semaphore's count by. |
52 | |
53 | =item up |
54 | |
55 | =item up NUMBER |
56 | |
57 | The C<up> method increases the semaphore's count by the number specified, |
58 | or one if no number's been specified. This will unblock any thread blocked |
59 | trying to C<down> the semaphore if the C<up> raises the semaphore count |
60 | above what the C<down>s are trying to decrement it by. |
61 | |
62 | =back |
63 | |
d516a115 |
64 | =cut |
65 | |
d21067e0 |
66 | sub new { |
67 | my $class = shift; |
68 | my $val = @_ ? shift : 1; |
69 | bless \$val, $class; |
70 | } |
71 | |
ee8c7f54 |
72 | sub down : locked : method { |
d21067e0 |
73 | my $s = shift; |
0a00ffdb |
74 | my $inc = @_ ? shift : 1; |
75 | cond_wait $s until $$s >= $inc; |
76 | $$s -= $inc; |
d21067e0 |
77 | } |
78 | |
ee8c7f54 |
79 | sub up : locked : method { |
d21067e0 |
80 | my $s = shift; |
0a00ffdb |
81 | my $inc = @_ ? shift : 1; |
82 | ($$s += $inc) > 0 and cond_broadcast $s; |
d21067e0 |
83 | } |
84 | |
85 | 1; |