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