small medium large xlarge

15 Jul 2013, 03:42
Dave Thomas (389 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?
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.

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.

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.

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()
    |> ->
      spawn_link fn ->
        IO.puts "me = #{inspect me}"
        IO.puts "self = #{inspect self()}"
        (send me, {self(), fun.(elem)}) end
    |> (pid) ->
      receive do {^pid, result} -> result end

You must be logged in to comment