Perl threading: Why does the output come by order and not mixed-up?

Viewed 77

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

1 Answers

You created a single thread. Create more threads to experience asynchronicity.

my @threads = map threads->create(
    ...
), 1 .. 4;

...

$_->join for @threads;
Related