3

Me and my friend was trying to find a bug with our code for some time when we realised that this was the problem:

random_function(spawn_link(fun() -> worker(List, self(), Death) end));

This was the solution:

PID = self(),
random_function(spawn_link(fun() -> worker(List, PID, Death) end));

So my question is, why did it not work to just call the self()-function straight away like that? Is it because it's an anonymous function or is it some kind of special Erlang thing?

Simon
  • 470
  • 1
  • 7
  • 22

3 Answers3

5

It is a bit more subtle. The self() call happens inside the fun() which is spawned. Since it it spawned, it has another Pid than the one you expect. Hence, the semantics are different.

I GIVE CRAP ANSWERS
  • 18,739
  • 3
  • 42
  • 47
  • Oh okey so it gets the PID of the anonymous function? But wouldn't that function be called within the process that called spawn_link? Or is the anonymous function first spawned as a separate process and then that one is giving spawn_link its argument instead of the process actually calling spawn_link? – Simon Mar 08 '14 at 17:04
  • @Simon No, `spawn_link` spawns a process and then _that process_ executes the function passed as `spawn_link`'s argument. – Alexey Romanov Mar 08 '14 at 17:25
0

you should know that spawn_link(fun() -> worker(List, self(), Death) will create a new process, we just call it Pid1, then self() stands for Pid1.

In the second case, you can Pid = self() outside the spawn function, so self() just stand for Pid.

BlackMamba
  • 10,054
  • 7
  • 44
  • 67
0

When you spawn/spawn_link a fun then the body of the fun is evaluated in the new process, not in the spawning process. This is what is happening in your first case, the self() call is evaluated in the new process so it does not return the value you want, the pid of the spawning process. However, in your second case you first evaluate self() in the spawning process and then pass that pid into the new process, which is what you want.

This is actually a common mistake.

rvirding
  • 20,848
  • 2
  • 37
  • 56