我想 fork 5 个进程,每个进程都会为一个小函数创建 100 个线程。问题是这个函数正在生成许多我想在哈希中捕获的值。我能够处理单个进程并创建 100 个线程,但无法处理多个线程。我正在 Perl 中执行此操作,并使用线程 CPAN 模块来实现相同的目的。
最佳答案
一种不 fork 多个线程,一种 fork 进程。每个新进程都在自己的内存空间中运行,并且更改一个进程中的任何变量值不会影响任何其他进程中的这些值。为了做你想做的事,你将需要某种进程间通信。
实现此目的的一种简单方法是让每个子进程将其输出写入文件,并在子进程完成时让父进程读取该文件。如果您注意并发问题,您甚至可以让所有子级写入同一个文件:
sub write_child_output_to_file {
my ($msg, $file) = @_;
open my $fh, '>>', $file;
flock $fh, 2;
seek $fh, 0, 2;
print $fh $msg;
close $fh;
}
Forks::Super
模块具有可以为您处理这些细节的功能:
use Forks::Super;
use Data::Dumper;
my %foo;
for my $i (1 .. 5) {
fork {
share => [ \%foo ],
sub => {
# the code that will run in each child process.
# Updates to the variable %foo in the child will be
# available to the parent when the child finishes
...
}
};
}
waitall;
print "Data produced in all the children: ",
Data::Dumper::Dumper(\%foo);
关于multithreading - Perl Fork 线程捕获输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9193589/