繁体   English   中英

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

[英]Erlang dynamic variable names on each iteration

程序正在运行。 最简单的解决方案是最好的。 注册的流程无效。 我实际上在从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.

您不能直接命名Pid。 你可以把一个进程名称,但是, 注册使用其register/2 但是,您应该小心,因为注册的进程名称必须是一个原子,如果不小心,您有可能填写原子表

%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).

如果您需要一个清单,为什么还要命名呢? 您可以执行以下操作:

%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).

这将返回一个Pid列表,而无需其他辅助函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM