Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Erlang, what's the difference between gen_server:start() and gen_server:start_link()?

Can someone explain what's the difference between gen_server:start() and gen_server:start_link()?

I've been told that it's something about multi threading stuff.

EDIT: If my gen_server is called from multiple threads, will it execute them all at once ? Or will it create concurrency between these threads?

like image 357
Guga Melkadze Avatar asked Jul 12 '16 11:07

Guga Melkadze


2 Answers

Both functions start new gen_server instances as children of the calling process, but they differ in that the gen_server:start_link/3,4 atomically starts a gen_server child and links it to its parent process. Linking means that if the child dies, the parent will by default also die. Supervisors are parent processes that use links to take specific actions when their child processes exit abnormally, typically restarting them.

Other than the linking involved in the gen_server:start_link case, there are no multi-process aspects involved in these calls. Regardless of whether you use gen_server:start or gen_server:start_link to start a new gen_server, the new process has a single message queue, and it receives and processes those messages one at a time. There is nothing about gen_server:start_link that causes the new gen_server process to behave or perform differently than it would if started with gen_server:start.

like image 60
Steve Vinoski Avatar answered Nov 08 '22 16:11

Steve Vinoski


When you use gen_server:start_link new process becomes "child" of calling process - it's part of supervision tree. It allows calling process to be notified if gen_server process dies.

Using gen_server:start will spawn process outside of supervision tree.

Nice description of supervision in Erlang is here: http://learnyousomeerlang.com/supervisors

like image 5
Novakov Avatar answered Nov 08 '22 17:11

Novakov