I'm new to Perl and I'm trying to understand how to use threads correctly.
Why does the following code print by order (as I would expect if no threads were involved) and not mixed?
my $q = Thread::Queue->new();
my $thr = threads->create(
sub {
while ( defined(my $InstPort = $q->dequeue())) {
my $waiting = 0;
while ($waiting < 999) {
print("num = $InstPort \n");
$waiting = $waiting + 1;
}
}
}
);
$q->enqueue(1,2,3,4,5);
$q->end();
$thr->join();
Output:
1
1
... // 999 times
2
2
... // 999 times
3
3
... // 999 times
4
4
... // 999 times
5
5
... // 999 times
I referenced from the following websites: https://www.perlmonks.org/?node_id=1068673 https://metacpan.org/pod/Thread::Queue