Why is spawn_link necessary in Erlang?

≯℡__Kan透↙ 提交于 2020-01-23 12:53:39

问题


I understand that if you do spawn followed by link, the process may have died in the mean time. Why is that a problem? Can't link see that you're trying to link to a process that has already died? In that case couldn't it just behave as though the remote process died immediately after link was called?

I think it would be nice if you could do spawn and link separately, and not have to do them together in one atomic function, because a) that would make the language more orthogonal (spawn_link heavily overlaps with spawn and link) b) if I have a start function that's basically just a wrapper around spawn, I ALSO need to supply start_link. So the non-orthogonality is viral. Yuck!


回答1:


Remember that links are bidirectional, so consider the case where process A spawns process B but then dies before being able to link to B. In this case, B has no idea that it is not linked to A, and it does not die when A dies.

With spawn_link this scenario can't happen because the spawn and link either occur together atomically, or they both fail.




回答2:


Another reason, which cannot be emulated:

If a process is trapping exit signals, then if first spawns and then tries to link to a process that dies immediately, the failed link will result in a {'EXIT',..., noproc} exit signal.

If spawn_link is used, however, the exit signal will always carry the real exit reason.



来源:https://stackoverflow.com/questions/28531101/why-is-spawn-link-necessary-in-erlang

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!