gpt4 book ai didi

multithreading - Perl线程递增变量

转载 作者:行者123 更新时间:2023-12-03 13:16:01 25 4
gpt4 key购买 nike

我有以下Perl代码::

#!/usr/bin/perl

use threads;
use Thread::Queue;
use DateTime;

$| = 1; my $numthreads = 20;

$min = 1;
$max = 100;

my $fetch_q = Thread::Queue->new();
our $total = 0;
sub fetch {
while ( my $target = $fetch_q->dequeue() ) {
print $total++ . " ";
}
}

my @workers = map { threads->create( \&fetch ) } 1 .. $numthreads;

$fetch_q->enqueue( $min .. $max );
$fetch_q->end();

foreach my $thr (@workers) {$thr->join();}

该代码创建20个线程,然后递增变量 $total

当前输出类似于:
0 0 0 0 0 1 0 0 1 1 2 0 0 1 0 2 0 3 0 1 0 2 1 0 2 1 0 0 3 0

但是所需的输出是:
1 2 3 4 5 6 7 8 9 10 .... 30

有没有办法让Perl增加变量?顺序无关紧要(即如果为1 2 4 5 3则可以)。

最佳答案

use threads::shared;


my $total :shared = 0;


lock $total;
print ++$total . " ";

关于multithreading - Perl线程递增变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31080945/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com