while ($thr->is_running() {
# do something
}
VS
while (! $thr->joinable()) {
# do something
}
两者之间有什么区别吗? 程序员何时使用一个而不是另一个,反之亦然?
我假设你不能加入一个线程,如果它运行,所以他们基本上是相同的东西?
如果是这样,为什么perl提供了两种不同的方法来检查线程的状态?
答案 0 :(得分:6)
is_joinable
与!is_running
不同。
is_joinable
检查
(thread->state & PERL_ITHR_FINISHED) &&
!(thread->state & PERL_ITHR_DETACHED) &&
!(thread->state & PERL_ITHR_JOINED)
is_running
检查
!(thread->state & PERL_ITHR_FINISHED)
所以
答案 1 :(得分:2)
根据文件:
$thr->is_running()
Returns true if a thread is still running
(i.e., if its entry point function has not yet finished or exited).
$thr->is_joinable()
Returns true if the thread has finished running,
is not detached and has not yet been joined. In other words,
the thread is ready to be joined, and a call to $thr->join() will not block.
因此差异源于分离线程的处理方式。 即$ thread-> is_running()如果线程正在运行则返回true,无论它是否已分离
但是"不是$ thread-> is_joinable()"即使线程已分离但已停止运行,它也会返回true。
示例:
1)分离的线程
use strict;
use warnings;
use threads;
sub do_nothing {
print("in thread\n");
sleep(30);
return;
}
my $t = threads->create(\&do_nothing);
$t->detach();
while ($t->is_running()) {
print("is running\n");
sleep(4);
}
if ($t->is_joinable()) {
print("is joinable\n");
}
else {
print("not joinable\n");
}
exit;
示例:非分离线程
use strict;
use warnings;
use threads;
sub do_nothing {
print("in thread\n");
sleep(30);
return;
}
my $t = threads->create(\&do_nothing);
while ($t->is_running()) {
print("is running\n");
sleep(4);
}
if ($t->is_joinable()) {
print("is joinable\n");
}
else {
print("not joinable\n");
}
exit;
答案 2 :(得分:1)
它们不一样。
如果线程尚未加入或分离,并且不再运行,则该线程是“可连接的”。也就是说,它为连接线程阻塞的条件提供了一个轮询接口。
已完成运行,尚未加入,未分离==可加入
尚未完成运行,尚未加入,未分离==正在运行。
请参阅Perl Threads。