如何在Perl中处理具有依赖项的调度线程? [英] How can I handle scheduling threads with dependencies in Perl?

查看:69
本文介绍了如何在Perl中处理具有依赖项的调度线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下情况:

sub_1 can run immediately
sub_2 can run immediately
sub_3 can run only after sub_1 finishes
sub_4 can run only after sub_1 finishes
sub_5 can run only after sub_2 finishes
sub_6 can run only after sub_2 finishes
sub_7 can run only after both sub_1 and sub_2 finish
sub_8 can run only after both sub_1 and sub_2 finish

我希望每个潜艇尽快开始运行,而不是等待它们全部完成.

I would like each sub to start run as soon as possible, than wait for all of them to finish.

非常感谢您为这个简单的方案提供了一个干净的解决方案-我是多线程技术的新手.

I would really appreciate you help in creating a clean solution for this simple scenario -- I'm new to multi-threading.

我不确定是否会有所不同,但是这些子对象都在对象中.

I'm not sure if it makes a difference, but those subs are all in an object.

推荐答案

我建议使用老板/工人"模型,其中一个线程管理将在工作线程中执行的子例程,然后该子例程将其状态报告给完成后的老板.

I'd suggest a "Boss/Worker" model, wherein one thread manages the subroutines to be executed in worker threads, who in turn report their status back to the boss upon completion.

在此模型中,boss是唯一需要知道如何订购任务的线程.它可能看起来像这样:

In this model the boss is the only thread that needs to know how tasks are to be ordered. It might look something like this:

use threads;
use Thread::Queue;
use Thread::Pool;

our $done_queue = Thread::Queue->new;
our $work_pool  = Thread::Pool->new;

sub sub_1 {
  ... do the work ...
  $done_queue->enqueue('sub_1'); # tell the boss we're all done
}

sub sub_2 {
  ... do the work ...
  $done_queue->enqueue('sub_2'); # tell boss we're done
}

...

# Main loop (boss thread)

$work_pool->enqueue(\&sub_1);
$work_pool->enqueue(\&sub_2);

while (my $sub_name = $done_queue->dequeue) {
  # You, the boss thread, keep track of state and
  # transitions however you like.  You know what's
  # just finished and what's finished in the past
  ...
}

当然,抽象可以使整洁—您可以将Pool和Queue隐藏在单个对象后面,而该对象根本不需要sub_1()即可了解状态队列:

Of course, abstraction can make that neater -- you could hide the Pool and the Queue behind a single object, one which didn't require sub_1() to know about the status queue at all:

$boss->enqueue( 'sub_1' => \&sub_1 ); # Will return 'sub_1' via await_completed()
$boss->enqueue( 'sub_2' => \&sub_2 ); # Will return 'sub_1'

while (my $sub_name = $boss->await_completed) {
  ...
}

这篇关于如何在Perl中处理具有依赖项的调度线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆