Leaked source code of windows server 2003
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

85 lines
2.3 KiB

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