下面是使用線程和線程共享一個可能的解決方案。大部分代碼只是模擬測試並模擬在完成之前必須「工作」的線程。在這個例子中,主線程產生了七個線程,每個線程都有一個隨機的時間量,他們必須做「工作」。線程無法開始工作,直到他們依賴的其他線程(在依賴關係數組中設置)完成。您可以更改線程依賴關係並運行示例幾次,以說明它可以正常工作。
此外,您可以讓每個線程終止運行後有主線程終止後,所有的子線程都通過檢查狀態哈希完成。
use strict;
use warnings;
use threads;
use threads::shared;
my %status : shared;
my $dependencies = [
{3 => 1}, #three can only run after one has finished...
{4 => 1}, #four can only run after one has finished...
{5 => 2}, #five can only run after two has finished...
{6 => 1}, #etc...
{6 => 2},
{7 => 1},
{7 => 2}
];
main();
sub main{
foreach my $thread_number (1..7){
spawn_thread($thread_number);
}
while(1){
print "I am the main thread\n";
sleep(1);
}
}
sub spawn_thread{
my $thread_number = shift;
$status{$thread_number} = 'wait';
my $thr = threads->new(\&thread_routine, $thread_number);
}
sub thread_routine{
my $thread_number = shift;
my $working_time_left = int(rand(5)) + 1; #make a random time that this thread needs to "work"
while(1){
print "I am thread number $thread_number with status $status{$thread_number}\n";
{
lock(%status);
#see if this thread is active; if so, see if it finished running running
if ($status{$thread_number} eq 'active'){
if ($working_time_left <= 0){
$status{$thread_number} = 'ran';
}
}
else{
#see if we can activate
if ($status{$thread_number} eq 'wait'){
my $can_activate = 1;
foreach my $index (0..$#$dependencies){
if (exists $dependencies->[$index]->{$thread_number}){
if ($status{$dependencies->[$index]->{$thread_number}} ne 'ran'){
$can_activate = 0;
last;
}
}
}
if ($can_activate){
$status{$thread_number} = "active";
}
}
}
}
sleep(1);
if ($status{$thread_number} eq 'active'){ #do "work"
$working_time_left--;
}
}
}
您已指定'sub_6'條件兩次,且條件部分重疊 - 是一個錯誤? – pilcrow 2010-08-10 13:59:24
@pilcrow謝謝,我更正了這個 – 2010-08-10 14:04:33