This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
fixes for pod noises
[perl5.git] / ext / Thread / Thread / Semaphore.pm
CommitLineData
d21067e0
MB
1package Thread::Semaphore;
2use Thread qw(cond_wait cond_broadcast);
3
d516a115
JH
4=head1 NAME
5
6Thread::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
HM
21=head1 DESCRIPTION
22
23Semaphores provide a mechanism to regulate access to resources. Semaphores,
24unlike locks, aren't tied to particular scalars, and so may be used to
25control access to anything you care to use them for.
26
27Semaphores don't limit their values to zero or one, so they can be used to
28control access to some resource that may have more than one of. (For
29example, filehandles) Increment and decrement amounts aren't fixed at one
30either, 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
40C<new> creates a new semaphore, and initializes its count to the passed
41number. If no number is passed, the semaphore's count is set to one.
42
43=item down
44
45=item down NUMBER
46
47The C<down> method decreases the semaphore's count by the specified number,
48or one if no number has been specified. If the semaphore's count would drop
49below zero, this method will block until such time that the semaphore's
50count is equal to or larger than the amount you're C<down>ing the
51semaphore's count by.
52
53=item up
54
55=item up NUMBER
56
57The C<up> method increases the semaphore's count by the number specified,
58or one if no number's been specified. This will unblock any thread blocked
59trying to C<down> the semaphore if the C<up> raises the semaphore count
60above what the C<down>s are trying to decrement it by.
61
62=back
63
d516a115
JH
64=cut
65
d21067e0
MB
66sub new {
67 my $class = shift;
68 my $val = @_ ? shift : 1;
69 bless \$val, $class;
70}
71
72sub down {
73 use attrs qw(locked method);
74 my $s = shift;
0a00ffdb
MB
75 my $inc = @_ ? shift : 1;
76 cond_wait $s until $$s >= $inc;
77 $$s -= $inc;
d21067e0
MB
78}
79
80sub up {
81 use attrs qw(locked method);
82 my $s = shift;
0a00ffdb
MB
83 my $inc = @_ ? shift : 1;
84 ($$s += $inc) > 0 and cond_broadcast $s;
d21067e0
MB
85}
86
871;