【问题标题】:Only one active thread after forking by Parallel::ForkManager. Why?Parallel::ForkManager 分叉后只有一个活动线程。为什么?
【发布时间】:2014-10-03 10:35:48
【问题描述】:

通过 Parallel::Fork: 分叉后,我只有一个工作线程:

ps -ef | grep ./BuildReportIndexV_VR2.pl

503      15955  9531 18 13:11 pts/0    00:02:06 /usr/bin/perl ./BuildReportIndexV_VR2.pl promt_tenant=AD backward=1
503      16102 15955 99 13:13 pts/0    00:09:29 /usr/bin/perl ./BuildReportIndexV_VR2.pl promt_tenant=AD backward=1
503      16103 15955  0 13:13 pts/0    00:00:02 /usr/bin/perl ./BuildReportIndexV_VR2.pl promt_tenant=AD backward=1
503      16104 15955  0 13:13 pts/0    00:00:02 /usr/bin/perl ./BuildReportIndexV_VR2.pl promt_tenant=AD backward=1
503      16105 15955  0 13:13 pts/0    00:00:03 /usr/bin/perl ./BuildReportIndexV_VR2.pl promt_tenant=AD backward=1

进程 15955 是父进程,16102 及以下是子进程。

以下是相关代码:

my $pm = Parallel::ForkManager->new($MAX_PROCESSES);
$pm->set_max_procs( $MAX_PROCESSES );

my $start_index;
my $last_index;

for ( $start_index = 0,
      $last_index=$start_index+$subhash_size-1;

      $last_index <= keys %$index_hr;

      $start_index=$last_index+1, $last_index=$start_index+$subhash_size-1
    )
{
    $pm->start and next;
    create_report_subprocess( $index_hr, $start_index, $last_index );
    $pm->finish;
}
$pm->wait_all_children;

print "After all children are waited: last index: $last_index\n";
if ( $last_index > keys %$index_hr) {
    $last_index = keys %$index_hr;
    create_report_subprocess( $index_hr, $start_index, $last_index );
} 

我设置了 $MAX_PROCESSES=4。

我预计所有 4 个线程都在运行。为什么只有一个?

【问题讨论】:

  • 这些是进程,而不是线程。所以其中3个没有使用cpu;大概他们正在等待什么。你知道他们在等什么吗?
  • 它们与运行的进程相同。没有不同。这就是问题所在:为什么 4 个等效线程中只有一个占用了整个 CPU?
  • create_report_subprocess 是做什么的?第一个完成工作后,会发生什么?
  • 从(子)哈希计算值,从 $start_index 开始,到 $last_index 结束。
  • 根本没有数据库或文件交互?只是计算?

标签: multithreading perl fork


【解决方案1】:

尝试在 for 循环之前为任何活动的数据库或语句句柄设置 AutoInactiveDestroy

【讨论】:

  • 它没有帮助,但问题确实出在数据库连接上。在父进程中关闭 DBI 连接后,所有子进程都在所有 CPU 上运行。这种情况应该怎么处理?
  • @rlib - 阅读有关分叉的 DBI 文档 - 无论如何,没有实用的方法可以在不同进程之间共享单个数据库连接。
  • 我怀疑你错过了一个活动句柄。确保您的 DBD::Pg 版本支持 AutoInactiveDestroy,尝试打开 metacpan.org/pod/DBI#TRACING 并查看子进程实际在做什么。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-14
  • 1970-01-01
  • 2010-10-11
  • 1970-01-01
  • 1970-01-01
  • 2015-05-08
相关资源
最近更新 更多