zhulinpinyu / zhulinpinyu.github.io

Blog
http://blog.zhulinpinyu.com
Apache License 2.0
2 stars 0 forks source link

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

Open zhulinpinyu opened 6 years ago

zhulinpinyu commented 6 years ago
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