Perl 线程:为什么输出是按顺序而不是混淆的?

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

我是 Perl 的新手,我正在尝试了解如何正确使用线程。

为什么以下代码按顺序打印(如我所料,如果不涉及线程)而不是混合打印?

    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();

输出:

1
1
... // 999 times
2
2
... // 999 times
3
3
... // 999 times
4
4
... // 999 times
5
5
... // 999 times

我参考了以下网站: https://www.perlmonks.org/?node_id=1068673 https://metacpan.org/pod/Thread::Queue

您创建了一个线程。创建更多的线程来体验异步。

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

...

$_->join for @threads;