Reputation:
Program is working now. The simplest solution was the best. The registered processes did not work. I actually was having some trouble with the call to await/2 from the base case of start/6. Turned out I was using the modified list 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.
Upvotes: 0
Views: 415
Reputation: 10841
You cannot name Pids directly. You can take a process name, however, and register it using register/2
. You should be careful, though, because the registered process name needs to be an atom and you could potentially fill up the atom table if you aren't careful.
%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).
If you need a list of Pids, why name them at all? You could do something like this:
%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).
This would return a list of Pids without the need of the other helper function.
Upvotes: 1