2012-02-08 114 views
2

我想分叉5个进程,它们都会为一个小函数创建100个线程。问题是这个函数正在生成许多我想要在哈希中捕获的值。我可以使用单个进程并创建100个线程,但我无法处理多个线程。这是我在Perl中使用线程CPAN模块进行的。Perl fork fork线程捕获输出

+0

其实小功能是下载文件。我分叉了5个进程,然后每个进程使用WW :: Curl创建100个线程来下载文件。我不想使用WWW :: Curl :: Many模块,但只有这种方式。任何帮助将不胜感激! – user1065000 2012-02-08 12:57:47

回答

2

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

实现此目的的一种简单方法是让每个子进程将其输出写入文件,并让子进程在子进程结束时读取该文件。你甚至可以拥有所有的小朋友写同一个文件,如果你留意的并发问题:

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);