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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With