[erlang-questions] gen_server etc: blocking init, blocking cast
Sat Apr 16 08:36:59 CEST 2016
Thank you very much. That clears it up for me. :)
Gesendet: Samstag, 16. April 2016 um 07:25 Uhr
Von: Chandru <chandrashekhar.mullaparthi@REDACTED>
An: "Oliver Korpilla" <Oliver.Korpilla@REDACTED>
Cc: "Erlang-Questions Questions" <erlang-questions@REDACTED>
Betreff: Re: [erlang-questions] gen_server etc: blocking init, blocking cast
init is executing in the context of the spawned gen_server process. It sends itself a message (which is non-blocking) and the init function returns, which means the supervisor:init function finishes executing, and your application startup is complete. Now your gen_server callback handle_cast is immediately called which then calls the gen_tcp:accept blocking call. It is okay for this to be blocked, because that is the main purpose of this process - block until a connection is available. The blocking nature is a problem only in two situations.
1. Code upgrade tends to be a problem. If you update the module invoking the blocking gen_tcp:accept twice, with no intervening socket connections being accepted, the server process will be killed, because your process hasn't handled the code upgrade message.
2. The gen_server process handles any other application specific messages - which as you've surmised will be blocked.
I typically use the following pattern for accepting TCP connections.
This frees up your process which owns the listen socket (tcp_server.erl) to handle other messages as well. The process which is blocking (tcp_socket.erl) is not doing anything useful until it gets a TCP connection.
I hope this helps.
More information about the erlang-questions