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.

95 lines
2.2 KiB

  1. package Thread::Queue;
  2. use Thread qw(cond_wait cond_broadcast);
  3. =head1 NAME
  4. Thread::Queue - thread-safe queues
  5. =head1 SYNOPSIS
  6. use Thread::Queue;
  7. my $q = new Thread::Queue;
  8. $q->enqueue("foo", "bar");
  9. my $foo = $q->dequeue; # The "bar" is still in the queue.
  10. my $foo = $q->dequeue_nb; # returns "bar", or undef if the queue was
  11. # empty
  12. my $left = $q->pending; # returns the number of items still in the queue
  13. =head1 DESCRIPTION
  14. A queue, as implemented by C<Thread::Queue> is a thread-safe data structure
  15. much like a list. Any number of threads can safely add elements to the end
  16. of the list, or remove elements from the head of the list. (Queues don't
  17. permit adding or removing elements from the middle of the list)
  18. =head1 FUNCTIONS AND METHODS
  19. =over 8
  20. =item new
  21. The C<new> function creates a new empty queue.
  22. =item enqueue LIST
  23. The C<enqueue> method adds a list of scalars on to the end of the queue.
  24. The queue will grow as needed to accomodate the list.
  25. =item dequeue
  26. The C<dequeue> method removes a scalar from the head of the queue and
  27. returns it. If the queue is currently empty, C<dequeue> will block the
  28. thread until another thread C<enqueue>s a scalar.
  29. =item dequeue_nb
  30. The C<dequeue_nb> method, like the C<dequeue> method, removes a scalar from
  31. the head of the queue and returns it. Unlike C<dequeue>, though,
  32. C<dequeue_nb> won't block if the queue is empty, instead returning
  33. C<undef>.
  34. =item pending
  35. The C<pending> method returns the number of items still in the queue. (If
  36. there can be multiple readers on the queue it's best to lock the queue
  37. before checking to make sure that it stays in a consistent state)
  38. =back
  39. =head1 SEE ALSO
  40. L<Thread>
  41. =cut
  42. sub new {
  43. my $class = shift;
  44. return bless [@_], $class;
  45. }
  46. sub dequeue : locked : method {
  47. my $q = shift;
  48. cond_wait $q until @$q;
  49. return shift @$q;
  50. }
  51. sub dequeue_nb : locked : method {
  52. my $q = shift;
  53. if (@$q) {
  54. return shift @$q;
  55. } else {
  56. return undef;
  57. }
  58. }
  59. sub enqueue : locked : method {
  60. my $q = shift;
  61. push(@$q, @_) and cond_broadcast $q;
  62. }
  63. sub pending : locked : method {
  64. my $q = shift;
  65. return scalar(@$q);
  66. }
  67. 1;