Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When use Spawn and Spawn_link?

Tags:

erlang

When I need to create a process,I will use the customary spawn bif.But there is one more bif spawn_link that is often used to do the same thing.

So basically when should one use spawn and spawn_link?

like image 331
HIRA THAKUR Avatar asked Sep 29 '14 06:09

HIRA THAKUR


1 Answers

Doing spawn and then link manually is equivalent in operation to spawn_link, but it is not equivalent in time; in particular it is not atomic (as in, two independent operations, not a single, indivisible one). If you spawn a process and it dies in its initialization (whatever your start or init functions do) then it might die before the call to link completes, and the linked process will never get notified that the process died since it died before it was linked. Oops!

From Joe Armstrong's Programming Erlang Ch.13 "Why Spawning and Linking Must be an Atomic Operation":

Once upon a time Erlang had two primitives, spawn and link, and spawn_link(Mod, Func, Args) was defined like this:

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

Then an obscure bug occurred. The spawned process died before the link statement was called, so the process died but no error signal was generated. This bug took a long time to find. To fix this, spawn_link was added as an atomic operation. Even simple-looking programs can be tricky when concurrency is involved.

like image 80
zxq9 Avatar answered Nov 10 '22 11:11

zxq9