Guga  Melkadze
Guga Melkadze

Reputation: 285

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?

Upvotes: 12

Views: 3271

Answers (2)

Steve Vinoski
Steve Vinoski

Reputation: 20014

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.

Upvotes: 14

Novakov
Novakov

Reputation: 3095

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

Upvotes: 6

Related Questions