| 1 | use Thread; |
| 2 | use Thread::Queue; |
| 3 | |
| 4 | $q = new Thread::Queue; |
| 5 | |
| 6 | sub reader { |
| 7 | my $tid = Thread->self->tid; |
| 8 | my $i = 0; |
| 9 | while (1) { |
| 10 | $i++; |
| 11 | print "reader (tid $tid): waiting for element $i...\n"; |
| 12 | my $el = $q->dequeue; |
| 13 | print "reader (tid $tid): dequeued element $i: value $el\n"; |
| 14 | select(undef, undef, undef, rand(2)); |
| 15 | if ($el == -1) { |
| 16 | # end marker |
| 17 | print "reader (tid $tid) returning\n"; |
| 18 | return; |
| 19 | } |
| 20 | } |
| 21 | } |
| 22 | |
| 23 | my $nthreads = 3; |
| 24 | |
| 25 | for (my $i = 0; $i < $nthreads; $i++) { |
| 26 | Thread->new(\&reader, $i); |
| 27 | } |
| 28 | |
| 29 | for (my $i = 1; $i <= 10; $i++) { |
| 30 | my $el = int(rand(100)); |
| 31 | select(undef, undef, undef, rand(2)); |
| 32 | print "writer: enqueuing value $el\n"; |
| 33 | $q->enqueue($el); |
| 34 | } |
| 35 | |
| 36 | $q->enqueue((-1) x $nthreads); # one end marker for each thread |