每次迭代时的Erlang动态变量名称

时间:2015-04-23 00:03:38

标签: erlang

程序正在运行。最简单的解决方案是最好的。注册的流程无效。我实际上在从start / 6的基本情况调用await / 2时遇到了一些麻烦。原来我正在使用修改后的列表T_T。

%variables
T = 10000000,       
P = 4,              
Tpart = 2500000,            
Width = 1.0 / T,
Pi = pi(T, P, [], 1), calls pi/4 and gets a list of pid

start(T, P, Tpart, Width, Pi, 1). %calls start with the Pi variable which should contain 4 Pids



    % create a list of P Pids and return it
pi(_, P, List, Count) when Count > P -> List;
pi(T, P, List, Count) ->
Pid = spawn(pi, child, []),
Count2 = Count + 1,
pi(T,P, [Pid|List], Count2).


%start iterates through a list of Pids and sends a work order to each process
start(_, P, _, _, _, StaticList, Count) when Count > P -> await(StaticList, 0.0);
start(T, P, Tpart, Width, [Head|Tail], StaticList, Count) ->   
   Head ! {work, self(), P, Count, Tpart, Width},
   Count2 = Count + 1,
   start(T,P,Tpart,Width,Tail, StaticList, Count2).


%  Collects the partial sums from child processes. Print final output
await([], Final) -> io:format(" Final Sum: ~.8f \n", [(Final * 4.0)]);
await([Pid | Rest], Final) ->
    receive
        {done, Pid, Sum} ->
        Partial = Final + Sum,
        await(Rest, Partial)
    end.

1 个答案:

答案 0 :(得分:1)

您无法直接命名Pids。但是,您可以使用register/2获取流程名称,register。但是,您应该小心,因为注册的进程名称必须是一个原子,如果您不小心,可能会fill up the atom table

%Call to function
Pi = pi(T,P, [], 1, getName(1)), %list of Pids

% This is the main function that should return a list of Pid's with different names. 
pi(T, P, List, Count) when Count >= P -> List;
pi(T, P, List, Count) ->
Pid = spawn(pi, child, []), % I want to have name be: Pidx = ...
Count2 = Count + 1,
Name = getName(Count2),
register(Name,Pid),
pi(T,P, [Name|List], Count2).


%Helper method that returns an atom. I want to use this as a variable name in the main function.
getName(Count) ->
X = "Pid",
Y = integer_to_list(Count),
Name = X ++ Y,
list_to_atom(Name).

如果您需要Pids列表,为什么要给它们命名?你可以这样做:

%Call to function
Pi = pi(T,P, [], 1, getName(1)), %list of Pids

% This is the main function that should return a list of Pid's with different names. 
pi(T, P, List, Count) when Count >= P -> List;
pi(T, P, List, Count) ->
Pid = spawn(pi, child, []), % I want to have name be: Pidx = ...
Count2 = Count + 1,
pi(T,P, [Pid|List], Count2).

这将返回一个Pids列表,而不需要其他辅助函数。