Perl 线程:Sleep() 的行为如何
Perl Threads: How does Sleep() behave
我有以下 Perl 脚本,它创建 10 个线程并调用一个函数 1000 次。在这个函数中只有一个打印(用于调试)和 sleep(5)
这是 Perl 脚本:
use threads;
use threads::shared;
use Thread::Queue;
my $fetch_q = Thread::Queue->new();
sub fetch {
while ( my $num = $fetch_q->dequeue() ) {
print "$num\n";
sleep(5);
}
}
my @workers = map { threads->create( \&fetch ) } 1 .. 10;
$fetch_q->enqueue( 1 .. 1000 );
$fetch_q->end();
foreach my $thr (@workers) {$thr->join();}
当我调用 sleep(5)
时,整个程序似乎都停止了(这是正确的吗?)。另外,如何让单个线程休眠?
When I call sleep(5)
it seems like the entire program comes to a halt (is this correct?).
你是说每 5 秒只能看到一个数字吗?我每 5 秒看到 10 个数字,这意味着 sleep
只会让当前线程进入睡眠状态。
使用下面的程序可以看得更清楚:
use threads;
async {
print "Before sleep\n";
sleep 5;
print "After sleep\n";
};
async {
for (1..6) {
print "Boop\n";
sleep 1;
}
};
$_->join for threads->list;
输出:
Before sleep
Boop
Boop
Boop
Boop
Boop
After sleep
Boop
Also how would I make an individual thread sleep?
有很多方法可以在不使用 sleep
的情况下实现这一点,但我认为你 sleep
没有完全这样做是错误的。
我有以下 Perl 脚本,它创建 10 个线程并调用一个函数 1000 次。在这个函数中只有一个打印(用于调试)和 sleep(5)
这是 Perl 脚本:
use threads;
use threads::shared;
use Thread::Queue;
my $fetch_q = Thread::Queue->new();
sub fetch {
while ( my $num = $fetch_q->dequeue() ) {
print "$num\n";
sleep(5);
}
}
my @workers = map { threads->create( \&fetch ) } 1 .. 10;
$fetch_q->enqueue( 1 .. 1000 );
$fetch_q->end();
foreach my $thr (@workers) {$thr->join();}
当我调用 sleep(5)
时,整个程序似乎都停止了(这是正确的吗?)。另外,如何让单个线程休眠?
When I call
sleep(5)
it seems like the entire program comes to a halt (is this correct?).
你是说每 5 秒只能看到一个数字吗?我每 5 秒看到 10 个数字,这意味着 sleep
只会让当前线程进入睡眠状态。
使用下面的程序可以看得更清楚:
use threads;
async {
print "Before sleep\n";
sleep 5;
print "After sleep\n";
};
async {
for (1..6) {
print "Boop\n";
sleep 1;
}
};
$_->join for threads->list;
输出:
Before sleep
Boop
Boop
Boop
Boop
Boop
After sleep
Boop
Also how would I make an individual thread sleep?
有很多方法可以在不使用 sleep
的情况下实现这一点,但我认为你 sleep
没有完全这样做是错误的。