如何在Erlang中实现以下循环?

问题描述

我有以下伪代码

for ( int i = 0; i < V ; i++ )
{
  for( int j = 0 ; j < V ; j++ )
  {
    if( ( i != j ) && ( tuple {i,j} belong to E ) )
    {
      R[i] := {i,j};
    }
  }
}

我想使用来并行化此代码
如何使用Erlang来实现相同的目的? 我是Erlang的新手...

编辑:

我知道以下代码同时运行对say/2的两个调用

-module(pmap).

-export([say/2]).

say(_,0) ->
  io:format("Done ~n");

say(Value,Times) ->
  io:format("Hello ~n"),say(Value,Times-1).

start_concurrency(Value1,Value2) ->
  spawn(pmap,say,[Value1,3]),spawn(pmap,[Value2,3]).

但是,这里我们在对函数进行硬编码。因此,假设我想打电话say 1000次,我是否需要写spawn(pmap,[Valuex,3]) 1000次?我可以使用递归,但是会不会提供连续的性能

编辑:

我尝试了以下代码,目的是创建3个线程,每个线程都想运行一个say函数。我想同时运行这3个说函数(请在方框中进行评论以得到更多说明):

-module(pmap).

-export([say/1,test/1,start_concurrency/1]).

say(0) ->
  io:format("Done ~n");

say(Times) ->
  io:format("Hello ~p ~n",[Times]),say(Times-1).

test(0) ->
  spawn(pmap,[3]);

test(Times) ->
  spawn(pmap,[3]),test(Times-1).

start_concurrency(Times) ->
  test(Times).

代码正确吗?

解决方法

我想同时运行这3个说函数。这是代码吗 对吗?

您可以放弃您的start_concurrency(N)函数,因为它没有任何作用。相反,您可以直接致电test(N)

我打算创建3个线程

在erlang中,您创建processes

在erlang中,缩进为4个空格,而不是2个空格。

在函数定义的多个函数子句之间不要留空行。

如果要查看并发性,那么在同时运行的任务中必须等待一些时间。例如:

-module(a).
-compile(export_all).

say(0) ->
    io:format("Process ~p finished.~n",[self()]);
say(Times) ->
    timer:sleep(rand:uniform(1000)),%%perhaps waiting to receive data from an http request
    io:format("Hello ~p from process ~p~n",[Times,self()]),say(Times-1).

loop(0) ->
    spawn(a,say,[3]);
loop(Times) ->
    spawn(a,[3]),loop(Times-1).

在外壳中:

3> c(a).     
a.erl:2: Warning: export_all flag enabled - all functions will be exported
{ok,a}

4> a:loop(3).
<0.84.0>
Hello 3 from process <0.82.0>
Hello 3 from process <0.81.0>
Hello 2 from process <0.82.0>
Hello 3 from process <0.83.0>
Hello 2 from process <0.81.0>
Hello 3 from process <0.84.0>
Hello 2 from process <0.83.0>
Hello 1 from process <0.81.0>
Process <0.81.0> finished.
Hello 1 from process <0.82.0>
Process <0.82.0> finished.
Hello 2 from process <0.84.0>
Hello 1 from process <0.83.0>
Process <0.83.0> finished.
Hello 1 from process <0.84.0>
Process <0.84.0> finished.

5>

如果并发运行的任务中没有随机等待,则这些任务将按顺序完成:

-module(a).
-compile(export_all).

say(0) ->
    io:format("Process ~p finished.~n",[self()]);
say(Times) ->
    %%timer:sleep(rand:uniform(1000)),io:format("Hello ~p from process ~p~n",loop(Times-1).

在外壳中:

5> c(a).     
a.erl:2: Warning: export_all flag enabled - all functions will be exported
{ok,a}

6> a:loop(3).
Hello 3 from process <0.91.0>
Hello 3 from process <0.92.0>
Hello 3 from process <0.93.0>
Hello 3 from process <0.94.0>
<0.94.0>
Hello 2 from process <0.91.0>
Hello 2 from process <0.92.0>
Hello 2 from process <0.93.0>
Hello 2 from process <0.94.0>
Hello 1 from process <0.91.0>
Hello 1 from process <0.92.0>
Hello 1 from process <0.93.0>
Hello 1 from process <0.94.0>
Process <0.91.0> finished.
Process <0.92.0> finished.
Process <0.93.0> finished.
Process <0.94.0> finished.

7> 

如果并发运行的任务中没有随机等待,那么并发不会带来任何好处。