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

标签 multithreading perl sleep

我有一个基本的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/

相关文章:

performance - 给 Perl 的 print 一个列表或一个连接的字符串是否更快?

perl - 如何从另一个 PL/Perl 函数调用 PL/Perl 函数?

c - linux中sleep命令的使用

c++ - MFC C++ 在主线程上放置 1000 毫秒 sleep ?

java - 如何访问正在运行的线程的属性值

Java:我是否忽略了线程的要点? (线程内的对象)

c++ - 将指针传递给shared_ptr线程安全

Android工作线程不退出

python - 如何将 JSON 对象从 Perl 发送到 Python?

java - Thread.sleep() 中的奇怪行为