Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Perl:终止线程并获得迄今为止最好的结果_Perl_Multithreading - Fatal编程技术网

Perl:终止线程并获得迄今为止最好的结果

Perl:终止线程并获得迄今为止最好的结果,perl,multithreading,Perl,Multithreading,我对Perl线程相当陌生,因此我想知道在Perl中执行此操作的正确方法: for $input (@inputs) { push @threads, start_thread($input); } for $thread (@threads) { wait_for_external_event(); $thread->kick_thread_out_of_loop(); $result = $thread->result(); print $result

我对Perl线程相当陌生,因此我想知道在Perl中执行此操作的正确方法:

for $input (@inputs) {
  push @threads, start_thread($input);
}

for $thread (@threads) {
   wait_for_external_event();
   $thread->kick_thread_out_of_loop();
   $result = $thread->result();
   print $result;
}

sub my_thread {
  my $input = shift;
  while(1) {
    my $result = compute($best_result_so_far,$input);
    if($result > $best_result_so_far) {
      $best_result_so_far = $result;
    }
  }
  # The thread got kicked out of the loop
  return $best_result_so_far;
  do_some_cleanup_that_is_slow();
  exit thread;
}
我觉得将线程踢出计算循环的方法是使用信号并在线程中使用信号处理程序。但也许有更漂亮的方法可以做到这一点。我需要一些关于如何准确实现这一点的帮助,尤其是如何返回$best_result_至今为止,以及在返回后如何进行缓慢清理的帮助。这是非常重要的,我不必等待清理才能得到结果

---编辑---

我已经看过了教程,但找不到与正在运行的线程进行通信的示例(“join”只处理正在消亡的线程)。我是否可以从运行的线程返回结果,类似于:

for $input (@inputs) {
  push @threads, start_thread($input);
}

for $thread (@threads) {
   wait_for_external_event();
   $result = $thread->result();
   $thread->kill("KILL");
   print $result;
}

package ThreadObj;

sub my_thread {
  my $self = shift;
  my $input = shift;

  local $SIG{KILL} = sub {
    do_slow_cleanup();
    threads->exit();
  };

  while(1) {
    my $result = compute($best_result_so_far,$input);
    if($result > $self->{'best_result_so_far'}) {
      $self->{'best_result_so_far'} = $result;
    }
  }
}

sub result {
  my $self = shift;
  wait until (defined $self->{'best_result_so_far'});
  return $self->{'best_result_so_far'};
}

据我所知,不可能从线程返回结果并将线程清理延迟到以后

如果到目前为止,
$best\u result\u
在所有线程中都是通用的(如果只有一个最佳结果),那么
threads::shared
和信号量可能会有所帮助(尽管会以性能为代价)。有关一些好的初学者示例,请参见


感觉这个问题更适合基于事件的编程范式。可能是这个工作的合适工具?

我会使用一个或两个公共数据结构进行通信,其中每个线程使用自己的唯一id访问共享哈希中的一个条目以存储其当前结果。以同样的方式,使用第二个散列作为标志向线程发出退出时间的信号,或者使用一个公共标量,以防所有线程都必须同时退出。与无休止的循环不同,只要不设置标志,就可以循环。

听起来协同程序(按照Coro)确实比普通线程工作得更好。没有一个最佳结果。结果取决于输入,每个线程得到不同的输入。