【发布时间】:2014-06-21 10:49:20
【问题描述】:
我正在使用 fork 创建 9 个进程,我希望它运行:4 次打印“a selected.”,3 次打印“b selected”,2 次打印“c selected”。为此,我需要为每个运行案例减少一个计数器,并且我需要使用共享内存,但不知道如何,你能帮忙吗?
#!/usr/intel/bin/perl5.14.1
my $all_running = 9; #2+3+4
my @times_to_run = (4, 3, 2);
my (@children, @non_empty_cells);
# make an array which will save the indexes of cells in @times_to_run which aren't empty
for (my $i = 0; $i < scalar(@times_to_run); $i++) {
if ($times_to_run[$i] != 0) {
push(@non_empty_cells, $i);
}
}
while ($all_running > 0) { #run 5 times
my $pid = fork();
if (!defined($pid)) {
print("Fork Failed\n");
}
elsif ($pid > 0) {
#parent
push(@children, $pid);
sleep(0.5);
}
else { # child
# pick a non-empty cell
my $random_ = int(rand(@non_empty_cells));
if ($non_empty_cells[$random_] == 0) {
print "a chosen\n";
$times_to_run[0]--;
print "now $times_to_run[0]\n";
}
elsif ($non_empty_cells[$random_] == 1) {
print "b chosen \n";
$times_to_run[1]--;
print "now $times_to_run[1]\n";
}
else {
print "c chosen\n";
$times_to_run[2]--;
print "now $times_to_run[2]\n";
}
# update non empty-cells array
@non_empty_cells = ();
for (my $i = 0; $i < scalar(@times_to_run); $i++) {
if ($times_to_run[$i] != 0) {
push(@non_empty_cells, $i);
}
}
# print "now empty cells is : ".scalar(@non_empty_cells)."\n\n";
exit 0;
}
$all_running--;
}
foreach (@children) {
my $tmp = waitpid($_, 0);
}
【问题讨论】:
标签: perl shared-memory fork