我想以下面的代碼為例進行作業:
我想以下面的代碼為例進行作業。
my $milon;
my $pid = fork();
die if not defined $pid。
if (not $pid)
{
$milon>{$pid} = $pid;
exit;
}
$milon>{3}=4;
my $finished = wait();
print( "debug10: TEST =", Dumper($milon))。
輸出:
debug10: TEST = $VAR1 = {
'3' => 4: TEST = $VAR1 ={
};
我怎樣才能使字典同時保留3 => 4和$pid => $pid?
它不一定是分叉,它可以是多執行緒或非阻塞IO,根據你的想法,哪個更好就選哪個。
這是一個例子。
這當然是一個例子,我只是想從這個例子中總結出我的真實代碼。
uj5u.com熱心網友回復:
你需要一些執行緒/行程之間共享的記憶體。最簡單的可能是使用基于解釋器的threads和threads::shared。例如:
use threads。
use threads::shared;
my %milon :shared;
for (1 . . 2) {
threads->創建(sub{
my $tid = threads->tid()。
$milon{$tid} = $tid。
});
}
$milon{3} = 4;
$_->join for threads->list; # 等待所有執行緒完成。
print Dumper\%milon;
這樣的輸出:
$VAR1 = {
'1' => 1,
'2' => 2,
'3' => 4, '3' =>
};
uj5u.com熱心網友回復:
下面的示例代碼演示了使用fork()從陣列@numbers(共100個)中計算一個數字的square的并行執行。
REAPER函式分配給$SIG{CHLD}信號,清理已完成的子行程,以避免僵尸行程在行程表中閑逛。
調查fork()方法是否適合你的問題/任務。
use strict;
use warnings;
use POSIX qw(strftime :sys_wait_h)。
使用 Time::HiRes qw(usleep)。
my $limit = 10;
my $threads = $limit;
my @numbers = map { int(rand(100)) } 1...100。
sub REAPER{
local $!
while( (my $pid = waitpid(-1, WNOHANG) ) > 0 && WIFEXITED($? ) ) {
$threads ;
}
$SIG{CHLD} = &REAPER;
}
$SIG{CHLD} = &REAPER;
for ( @numbers ) {
while( $threads == 0 or $threads > $limit ) { usleep( 1 ) }
my $pid = fork();
die $! unless defined $pid;
if( $pid ) {
# parent; if( $pid ).
$threads--;
} else {
# child else {
my $n = compute_square($_)。
printf "Process m: = => %d
", $$, $_, $n;
exit 0;
}
}
sub compute_square{
my $num = shift;
return $num*$num;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/311374.html
標籤:
上一篇:Perlprintf的換行
下一篇:使用懶惰評估的perl腳本的解釋
