When using Spawn and Spawn_link?

When I need to create a process, I will use the usual spawn bif. But there is another bif spawn_link, which is often used to accomplish the same thing.

So basically when to use spawn and spawn_link ?

+6
source share
2 answers

Executing spawn and then link manually is equivalent in spawn_link operation, but it is not equivalent in time; in particular, it is not atomic (as, for example, by two independent operations, not one, not indivisible). If you create a process and die in its initialization (regardless of your start or init functions), it may die before the link call completes, and the related process will never receive a notification that the process has died since it died before it was connected. Unfortunately,

From Joe Armstrong Programming Erlang Ch.13 "Why spawning and communication should be an atomic operation":

Erlang once had two primitives, spawn and link , and spawn_link(Mod, Func, Args) defined as follows:

 spawn_link(Mod, Func, Args) -> Pid = spawn(Mod, Func, Args), link(Pid), Pid. 

Then an unclear error occurred. The initialized process died before the link operator was output, so the process died, but no error signal was generated. I found this mistake for a long time. To fix this, spawn_link was added as an atomic operation. Even simple programs can be complicated if concurrency is involved.

+11
source

spawn just spawns a new process.

spawn_link starts a new process and automatically creates a link between the calling process and the new process. Thus, it can be implemented as:

 my_spawn_link(Module, Function, Args) -> Pid = spawn(Module, Function, Args), link(Pid), Pid. 
+1
source

Source: https://habr.com/ru/post/975983/


All Articles