small medium large xlarge

Dave_gnome_head_isolated_pragsmall
15 Jul 2013, 03:42
Dave Thomas (390 posts)
  • In the pmap code, I assigned the value of self to the variable me at the top of the method, and then used me as the target of the message returned by the spawned processes. Why use a separate variable here?
Generic-user-small
09 Sep 2014, 04:58
Jingjing Duan (3 posts)

Otherwise, self will be pointing to the child process itself. “me” is available as a closure variable inside the child process pointing to the parent process.

Generic-user-small
07 Jan 2015, 18:56
Pierre Sugar (57 posts)

Jingjing, I think I came up with the same conclusion. I have also looked at the documentation but it is not very enlightening in this regard.

So my explanation is: The function fn -> (send me, { self, fun.(elem) }) end will be invoked in the newly spawned process. When it is invoked, me is the parent process and self at that time the child process. If send me would be changed to send self the child would send the message to itself.

Dave could you please confirm or correct this.

Generic-user-small
15 Mar 2016, 05:14
Tiago Motta Jorge (1 post)

I believe I’ve found the explanation: self is actually a function! Which means we can call it self(). That’s why Dave had to assign self() to a variable (me) before being able to use it inside the spawned process, otherwise he would have retrieved the PID of the spawned process, ‘cause self() inside the spawned_process would grab that process’s PID.

Generic-user-small
21 Mar 2017, 04:16
MJ (4 posts)

Self in spawn_link call point to the child process itself.

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

You must be logged in to comment