gpt4 book ai didi

multithreading - Perl:让线程进入休眠状态

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

我有一个基本的Perl脚本,该脚本运行具有20个线程的函数。

use threads;
use threads::shared;
use Thread::Queue;
use File::Slurp;

$| = 1; my $numthreads = 20;

my $fetch_q = Thread::Queue->new();
sub fetch {
while ( my $target = $fetch_q->dequeue() ) {
my $request = `curl "http://WEBSITE" -s -o /dev/null -w "%{http_code}"`; # Returns HTTP Status code of request (i.e. 200, 302, 404, etc)
if ($request eq "200") {
print "Success. Sleeping for 5 seconds.";
sleep(5);
}
else {
print "Fail. Will try again in 10 seconds.";
sleep(10);
redo;
}
}
}

my @workers = map { threads->create( \&fetch ) } 1 .. $numthreads;
$fetch_q->enqueue( 1 .. $max );
$fetch_q->end();
foreach my $thr (@workers) {$thr->join();}

如果条件为真,我希望线程休眠5秒,但让所有其他线程继续运行。现在,当我使用 sleep(5)时,整个脚本似乎休眠了5秒钟。

如何为各个线程使用 sleep()

最佳答案

sleep是正确的工具。我不知道您为什么认为它似乎阻塞了所有线程,但事实并非如此。下面说明了这一点:

use threads;
use threads::shared;

use Thread::Queue;

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

sub fetch {
while (defined( my $job = $fetch_q->dequeue() )) {
if ($job) {
print threads->tid, " Starting to sleep\n";
sleep(5);
print threads->tid, " Finished sleeping\n";
}
else {
print threads->tid, " Starting to sleep\n";
sleep(10);
print threads->tid, " Finished sleeping\n";
}
}
}

my @workers = map { threads->create( \&fetch ) } 1 .. 2;
$fetch_q->enqueue($_) for 0, 1, 1;
$fetch_q->end();
foreach my $thr (@workers) {$thr->join();}

输出:
1 Starting to sleep
2 Starting to sleep
2 Finished sleeping
2 Starting to sleep <-- The second job picked up work while the first was still sleeping.
1 Finished sleeping
2 Finished sleeping

关于multithreading - Perl:让线程进入休眠状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32260595/

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