1 package threads::shared::semaphore;
9 Thread::Semaphore - thread-safe semaphores
13 use Thread::Semaphore;
14 my $s = new Thread::Semaphore;
15 $s->up; # Also known as the semaphore V -operation.
16 # The guarded section is here
17 $s->down; # Also known as the semaphore P -operation.
19 # The default semaphore value is 1.
20 my $s = new Thread::Semaphore($initial_value);
26 Semaphores provide a mechanism to regulate access to resources. Semaphores,
27 unlike locks, aren't tied to particular scalars, and so may be used to
28 control access to anything you care to use them for.
30 Semaphores don't limit their values to zero or one, so they can be used to
31 control access to some resource that may have more than one of. (For
32 example, filehandles) Increment and decrement amounts aren't fixed at one
33 either, so threads can reserve or return multiple resources at once.
35 =head1 FUNCTIONS AND METHODS
43 C<new> creates a new semaphore, and initializes its count to the passed
44 number. If no number is passed, the semaphore's count is set to one.
50 The C<down> method decreases the semaphore's count by the specified number,
51 or one if no number has been specified. If the semaphore's count would drop
52 below zero, this method will block until such time that the semaphore's
53 count is equal to or larger than the amount you're C<down>ing the
60 The C<up> method increases the semaphore's count by the number specified,
61 or one if no number's been specified. This will unblock any thread blocked
62 trying to C<down> the semaphore if the C<up> raises the semaphore count
63 above what the C<down>s are trying to decrement it by.
71 my $val : shared = @_ ? shift : 1;
78 my $inc = @_ ? shift : 1;
79 cond_wait $s until $$s >= $inc;
86 my $inc = @_ ? shift : 1;
87 ($$s += $inc) > 0 and cond_broadcast $s;