Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top