gpt4 book ai didi

multithreading - 如何仅在perl中按需启动线程?

转载 作者:行者123 更新时间:2023-12-01 12:55:01 24 4
gpt4 key购买 nike

在 c# 中,我们可以创建线程并仅在需要时启动线程,如下所示(如果我是正确的)

Thread th=new thread("function");
th.start()

但是在 perl 中,当我创建它自己时它已经启动了。例如

$thread1=thread->create("function");

但我想创建 4 个线程。我应该只在需要时开始。我必须检查它是否正在运行?如果线程没有运行,那么我必须通过传递不同的参数来启动同一个线程。如何在 perl 中做到这一点?

最佳答案

可以将多个作业发送到队列中,它们正在等待轮到它们传递给工作人员。

use strict;
use warnings;
use threads;
use Thread::Queue;

my $no_of_workers = 4;
my $q = Thread::Queue->new();
# Worker thread
my @thr = map {

my $t = threads->create(sub{

# Thread will loop until no more work
while (defined(my $item = $q->dequeue())) {
# Do work on $item
print "$item\n";
}
});

{queue => $q, thread => $t, id => $_};

} 1 .. $no_of_workers;


# Send work to each thread
$_->{queue}->enqueue("Job for thread $_->{id}") for @thr;

for (@thr) {
# Signal that there is no more work to be sent
# $_->{queue}->end();

# similar to $queue->end() for older perl
$_->{queue}->enqueue(undef) for @thr;

# wait for threads to finish
$_->{thread}->join();
}

以循环方式将工作0..19分配给 worker ,

for my $i (0 .. 19) {
my $t = $thr[$i % @thr]; # $i % @thr => 0,1,2,3, 0,1,2,3, ..
$t->{queue}->enqueue("Job for thread $t->{id}");
}

关于multithreading - 如何仅在perl中按需启动线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21300780/

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