Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Elixir 使用process实现并发map运算 #5

Open
zhulinpinyu opened this issue Apr 11, 2018 · 0 comments
Open

Elixir 使用process实现并发map运算 #5

zhulinpinyu opened this issue Apr 11, 2018 · 0 comments
Labels

Comments

@zhulinpinyu
Copy link
Owner

defmodule Parallel do
  def pmap(collection, func) do
    me = self()

    collection
    |> Enum.map(fn e ->
      spawn_link(fn ->
        send(me, {self(), func.(e)})
      end)
    end)
    |> Enum.map(fn pid ->
      receive do
        {^pid, ret} -> ret
      end
    end)
  end

  def run(n) do
    IO.inspect(:timer.tc(Parallel, :pmap, [1..n, &(&1 * &1)]))
  end
end

运行:

screen shot 2018-04-11 at 19 09 44

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant