如果我启动多个线程,Perl 的线程连接方法是否会等待第一个线程完成?
foreach $name (@project_list)
{
# a thread is created for each project
my $t = threads->new(\&do_work, $name);
push(@threads, $t);
}
foreach (@threads) {
my $thrd = $_->join;
print "Thread $thrd done\n";
}
sub do_work {
# execute some commands here...
}
project_list 是包含 40 个项目的列表。当我为每个项目生成一个线程时, join 方法是否会等待第一个线程完成,然后移至下一个线程,依此类推?
如果是这样的话,那么是否可以避免呢?我的意思是有些线程会比其他线程完成得更快,所以为什么要等待呢?
如果需要更多信息,请告诉我。 谢谢。
foreach $name (@project_list)
{
# a thread is created for each project
my $t = threads->new(\&do_work, $name);
push(@threads, $t);
}
foreach (@threads) {
my $thrd = $_->join;
print "Thread $thrd done\n";
}
sub do_work {
# execute some commands here...
}
The project_list is a list of 40 items. When I spawn a thread for each item, will the join method wait for the first thread to finish and then move over to the next one and so on?
If that is the case, then is it possible to avoid it? I mean some threads will finish faster then others so why wait?
Please let me know if more information is required.
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
$_->join
等待$_
指定的线程完成。由于您按顺序推送它们,并且 foreach 按顺序遍历列表,所以您将首先等待第一个线程。但这并不重要,因为您正在等待所有线程完成。无论您先等待最快的完成者还是先等待最慢的完成者都没有关系 - 无论如何,您都会等待每个人。
$_->join
waits for the thread designated by$_
to finish. Since you're pushing them in order, andforeach
traverses the list in order, yes, you'll wait first for the first thread.But that doesn't matter since you're waiting for all threads to finish. It doesn't matter if you wait for the fastest finishers or the slowest ones first - you'll be waiting for everyone anyway.
为什么要等?这取决于后处理步骤的范围。
如果后处理步骤需要所有线程在开始工作之前完成,那么等待各个线程是不可避免的。
如果后处理步骤特定于每个线程的结果,则应该可以使后处理部分成为线程本身的一部分。
在这两种情况下,
$_->join foreach @threads;
都是可行的方法。如果不需要等待线程完成,请使用
detach
命令而不是join
。但是,线程可能返回的任何结果都将被丢弃。Why wait? It depends on the scope of the post-processing step.
If the post-processing step needs all threads to finish before beginning work, then the wait for individual threads is unavoidable.
If the post-processing step is specific to the results of each thread, it should be possible to make the post-processing part of the thread itself.
In both cases,
$_->join foreach @threads;
is the way to go.If there is no need to wait for the threads to finish, use the
detach
command instead ofjoin
. However, any results that the threads may return will be discarded.主线程必须在所有线程的持续时间内存活,因此您需要知道它们何时全部完成。可以通过队列或信号量来完成。信号量是最简单的:
The main thread has to live for the duration of all threads so you need to know when they are all done. The can be done queues or semaphores. Semaphores are the simplest: