Reputation: 25
I'm trying to change this method from sequential to concurrent:
seq(Y, Z) ->
P = Y+Z,
Q = Z*Y,
P/Q.
Here's what I have so far, I'm pretty confused right now so it probably doesn't make much sense.
P(Y, Z) -> Y+Z.
Q(Y, Z) -> Z*Y.
cc() ->
receive
{Y, Z} -> P(Y, Z)/Q(Y, Z)
end.
run() ->
pid = spawn(?MODULE, cc, []),
pid ! {10, 12}
Upvotes: 1
Views: 60
Reputation: 26121
p(Y, Z) -> Y+Z.
q(Y, Z) -> Z*Y.
cc(Y, Z) ->
Self = self(),
Pids = [spawn_link(fun() -> Self ! {self(), F(Y, Z)} end)
|| F <- [fun p/2, fun q/2]],
[P, Q] = [receive {Pid, Result} -> Result end || Pid <- Pids],
P/Q.
You can make it into "design pattern"
-module(cc).
-export([cc/2]).
-define(RUNCC_TIMEOUT, 5000).
-define(L(X), fun() -> X end).
runcc(Fs) ->
runcc(Fs, ?RUNCC_TIMEOUT).
runcc(Fs, Timeout) ->
Self = self(),
Pids = [spawn_link(fun() -> Self ! {self(), F()} end) || F <- Fs],
[receive {Pid, Result} -> Result after Timeout -> error(timeout) end
|| Pid <- Pids].
cc(Y, Z) ->
[P, Q] = runcc([?L(Y+Z), ?L(Y*Z)]),
P/Q.
Upvotes: 1