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
?
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
andlink
, andspawn_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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With