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

2

12

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?

Bani answered 12/7, 2016 at 11:11 Comment(0)
F
14

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.

Frieder answered 12/7, 2016 at 11:39 Comment(1)
I've already answered what's in your edit. If multiple processes call your gen_server concurrently, their messages are queued in the gen_server message queue, and the gen_server processes those messages one at a time.Frieder
A
5

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

Azerbaijani answered 12/7, 2016 at 11:17 Comment(3)
If my genserver is called from multiple threads, will it execute them all at once ? or will it create concurrency between theese threads?Bani
thanks for the answer, can you answer me on that as well?Bani
Erlang does not use term "thread". It's called "process". If multiple process call the same gen_server, they requests will be put into queue and handled one after another. On learnyousomeerlang.com/content there is very nice part about OTPAzerbaijani

© 2022 - 2024 — McMap. All rights reserved.