【问题标题】:Perl threading: Why does the output come by order and not mixed-up?Perl 线程:为什么输出是按顺序而不是混淆的?
【发布时间】:2021-08-12 11:34:45
【问题描述】:

我是 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

【问题讨论】:

    标签: multithreading perl


    【解决方案1】:

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

    my @threads = map threads->create(
        ...
    ), 1 .. 4;
    
    ...
    
    $_->join for @threads;
    

    【讨论】:

    • 嗨,我输入了下面的代码,仍然让它同步。我会检查我是否做错了什么,但是这种代码对你有用吗?
    • 是的,它对我有用。你有多少个 CPU 内核?
    • 运行以下命令后:lscpu | egrep 'Model name|Socket|Thread|NUMA|CPU(s)' 我得到:2 CPU(s) 1 Thread(s) per core: 2 Socket(s)
    猜你喜欢
    • 1970-01-01
    • 2012-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-11
    • 1970-01-01
    • 2019-08-06
    • 1970-01-01
    相关资源
    最近更新 更多