use Test::More tests => 21; # Test that Q.pm actually compiles. BEGIN { use_ok 'Q' }; # Test that the API as documented still exists. my $q = new_ok Q => [5]; can_ok $q => 'nq'; can_ok $q => 'dq'; can_ok $q => 'n'; # Thread to add some numbers to the queue. my $enqueue = threads->create(sub { $q->nq($_) for 90..99; }); # Vulnerable to race conditions :-( sleep 1; ok !$enqueue->is_joinable, '$q->nq is waiting'; # This breaks encapsulation by peeking at the internals of $q. # But we want to figure out if $q is waiting at '95'. ok !(grep { $_==95 } @$q), '95 is not on $q yet'; # Numbers come out of the thread in the correct order: is $q->dq, $_, "got $_ from queue" for 90..99; # Queue should now be empty, so not waiting for anything. sleep 1; ok $enqueue->is_joinable, '$q->nq is no longer waiting'; $enqueue->join; # Test that "dq" blocks too. my $dequeue = threads->create(sub { # Add up the numbers we get from the queue. my $sum; $sum += $q->dq for 1..10; return $sum; }); # We've not added any numbers to the queue yet, so the queue # should be waiting. sleep 1; ok !$dequeue->is_joinable, '$q->dq is waiting'; # Push some numbers into the queue. These sum to 55. $q->nq($_) for 1..10; # Queue should have recieved all the numbers. sleep 1; ok $dequeue->is_joinable, '$q->dq is no longer waiting'; my $sum = $dequeue->join; is $sum, 55, 'result of calculation performed in $dequeue is correct';