gpt4 book ai didi

multithreading - Perl Fork 线程捕获输出

转载 作者:行者123 更新时间:2023-12-03 13:00:48 25 4
gpt4 key购买 nike

我想 fork 5 个进程,它们都将为一个小函数创建 100 个线程。问题是这个函数正在生成许多我想在哈希中捕获的值。我能够处理单个进程并创建 100 个线程,但我无法处理多个线程。这是我在 Perl 中做的,并使用了相同的线程 CPAN 模块。

最佳答案

一个不 fork 多个线程,一个 fork 进程。每个新进程都在自己的内存空间中运行,并且在一个进程中更改任何变量值不会影响任何其他进程中的这些值。为了做你想做的事,你需要某种进程间通信。

实现这一点的一种简单方法是让每个子进程将其输出写入文件,并让父进程在子进程完成后读取该文件。如果您注意并发问题,您甚至可以让所有 child 写入同一个文件:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com