gpt4 book ai didi

multithreading - Perl:为要处理的线程正确传递数组

转载 作者:行者123 更新时间:2023-12-02 08:39:50 24 4
gpt4 key购买 nike

我正在学习如何在 Perl 中进行线程处理。我正在查看示例代码 here并稍微调整了解决方案代码:

#!/usr/bin/perl
use strict;
use warnings;
use threads;
use Thread::Semaphore;

my $sem = Thread::Semaphore->new(2); # max 2 threads
my @names = ("Kaku", "Tyson", "Dawkins", "Hawking", "Goswami", "Nye");
my @threads = map {
# request a thread slot, waiting if none are available:
foreach my $whiz (@names) {
$sem->down;
threads->create(\&mySubName, $whiz);
}
} @names;

sub mySubName {
return "Hello Dr. " . $_[0] . "\n";
# release slot:
$sem->up;
}

foreach my $t (@threads) {
my $hello = $t->join();
print "$hello";
}

当然,这个现在已经完全坏掉了,不行了。它导致此错误:

C:\scripts\perl\sandbox>threaded.pl
Can't call method "join" without a package or object reference at C:\scripts\perl\sandbox\threaded.pl line 24.
Perl exited with active threads:
0 running and unjoined
9 finished and unjoined
0 running and detached

我的目标有两个:

  • 强制在任何给定时间允许的最大线程数
  • 为线程提供“工作”数组

在最初的解决方案中,我注意到 0..100; 代码似乎指定了线程的“工作量”。但是,在我想提供一系列工作的情况下,我还需要提供类似的东西吗?

非常欢迎任何指导和更正。

最佳答案

您正在将 foreach 的结果存储到 @threads 而不是 threads->create 的结果。

即使您解决了这个问题,您收集已完成的线程也为时已晚。我不确定这个问题有多大,但它可能会阻止在某些系统上启动超过 64 个线程。 (64 是一个程序在某些系统上一次可以拥有的最大线程数。)

更好的方法是重用您的线程。这解决了您的两个问题并避免了重复创建线程的开销。

use threads;
use Thread::Queue 3.01 qw( );

use constant NUM_WORKERS => 2;

sub work {
my ($job) = @_;
...
}

{
my $q = Thread::Queue->new();

for (1..NUM_WORKERS) {
async {
while (my $job = $q->dequeue()) {
work($job);
}
};
}

$q->enqueue(@names); # Can be done over time.
$q->end(); # When you're done adding.
$_->join() for threads->list();
}

关于multithreading - Perl:为要处理的线程正确传递数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17636202/

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