Sequential method to concurrent method?

时间:2018-03-22 14:45:35

标签: erlang

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}

1 个答案:

答案 0 :(得分:1)

#include <iostream>
#include <vector>
using namespace std;
void search(vector<int> *v, int count, int node)
    {
       if (node == 4)
       {
        cout << "found 4";
       return;
    }

    if (node < count && !v[node].empty())
    {
        for (auto it = v[node].begin(); it != v[node].end(); it++)
        {
            search(v, count, *it);
        }
    }
}

int main()
{
   vector<int> v[5];
   v[1].push_back(2);
   v[1].push_back(3);
   v[2].push_back(4);
   v[2].push_back(5);

   search(v, sizeof(v) / sizeof(v[0]), 1);
   return 0;
}

您可以将其设置为&#34;设计模式&#34;

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.