Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elixir's parallel map algorithm

Tags:

elixir

I am currently working through "Programming Elixir" book, and just found this example of "map" implemented in a parallel manner:

defmodule Parallel do
  def pmap(collection, fun) do
    me = self
    collection
    |> Enum.map(fn (elem) ->
      spawn_link fn -> (send me, { self, fun.(elem) }) end end)
    |> Enum.map(fn (pid) ->
      receive do { ^pid, result } -> result end
    end)
  end
end

The comment to the code says: "Note how it uses ^pid in the receive block to get the result for each PID in turn. Without this we’d get back the results in random order.". Can someone clarify this?

like image 870
sixFingers Avatar asked Jun 04 '26 07:06

sixFingers


1 Answers

The ^ is called the pin operator. It matches with the previous value of the variable instead of rebinding it to the new value. So:

receive do
  {pid, result} -> result
end

receives any message of the form {whatever, whatever} and returns the second element from that tuple. But

receive do
  {^pid, result} -> result
end

receives any message that's a tuple and the first element is some exact value that's stored in pid.

like image 184
Paweł Obrok Avatar answered Jun 07 '26 11:06

Paweł Obrok



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!