相关疑难解决方法(0)

在Perl中,我如何等待线程并行结束?

我有一个Perl脚本,可以启动2个线程,每个处理器一个.我需要它等待一个线程结束,如果一个线程结束,则生成一个新线程.似乎join方法阻塞了程序的其余部分,因此第二个线程不能结束,直到第一个线程完成的所有操作都失败了.

我试过这个is_joinable方法,但似乎也没办法.

这是我的一些代码:

use threads;
use threads::shared;

@file_list = @ARGV;      #Our file list
$nofiles = $#file_list + 1; #Real number of files 
$currfile = 1;     #Current number of file to process

my %MSG : shared;              #shared hash

$thr0 = threads->new(\&process, shift(@file_list));
$currfile++;
$thr1 = threads->new(\&process, shift(@file_list));
$currfile++;

while(1){
 if ($thr0->is_joinable()) {
  $thr0->join;
        #check if there are files left to process
  if($currfile <= $nofiles){ 
   $thr0 = threads->new(\&process, shift(@file_list));
   $currfile++;
  }
 }

 if ($thr1->is_joinable()) {
  $thr1->join;
        #check if there are …
Run Code Online (Sandbox Code Playgroud)

perl multithreading locking join

8
推荐指数
2
解决办法
7809
查看次数

在Erlang中获取生成函数的结果

我目前的目标是编写计算N个元素列表的Erlang代码,其中每个元素都是它的"索引"的因子(因此,对于N = 10,我想得到[1!,2!,3!, ......,10!]).更重要的是,我希望每个元素都能在一个单独的过程中计算出来(我知道它只是效率低下,但我希望能够实现它并将其效率与其他方法进行比较).

在我的代码中,我想使用一个函数作为给定N的"循环",对于N,N-1,N-2 ...产生一个计算阶乘(N)并将结果发送到某些"收集"的过程"函数,将收到的结果打包到列表中.我知道我的概念可能过于复杂,所以希望代码可以解释一下:

messageFactorial(N, listPID) ->
    listPID ! factorial(N).      %% send calculated factorial to "collector".

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
nProcessesFactorialList(-1) ->
    ok;
nProcessesFactorialList(N) ->
    spawn(pFactorial, messageFactorial, [N, listPID]),   %%for each N spawn...
    nProcessesFactorialList(N-1).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
listPrepare(List) ->            %% "collector", for the last factorial returns
    receive                     %% a list of factorials (1! = 1).
        1 -> List;
        X ->
            listPrepare([X | List])
    end.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
startProcessesFactorialList(N) ->
    register(listPID, spawn(pFactorial, listPrepare, [[]])),
    nProcessesFactorialList(N).
Run Code Online (Sandbox Code Playgroud)

我想它会起作用,我的意思是listPrepare最终会返回一个阶乘列表.但问题是,我不知道如何获得该列表,如何获得它返回的内容?至于现在我的代码返回ok,因为这是nProcessesFactorialList在完成时返回的内容.我想到最后将listPrepare的结果列表发送到nProcessesFactorialList,但是它还需要是一个注册过程,我不知道如何恢复该列表.

基本上,如何从注册过程运行listPrepare(这是我的阶乘列表)中得到结果?如果我的代码根本不对,我会问一个如何让它变得更好的建议.提前致谢.

parallel-processing concurrency erlang functional-programming list

1
推荐指数
1
解决办法
1998
查看次数