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