[erlang-questions] How to solve the blocking accept call in a tcp_listener process ?

Ulf Wiger <>
Wed May 20 00:44:30 CEST 2009


Claes Wikstrom wrote:
> 
> The way I've always done it is to spawn the acceptor as:
> 
> L = listen(...),
> listen_loop(L).
> 
> 
> listen_loop(L) ->
>     Top = self(),
>     spawn(fun() ->
>             Sock = accept(L),
>             Top ! one_more,
>             handle_sock(Sock)
>            end),
>      receive
>         one_more ->
>            listen_loop(L)
>      end.

In newer versions of Erlang (since R11 or R12, not exactly sure),
you can have multiple acceptors on the same socket. We have found
this to be slightly faster:

listener(L) ->
    [spawn(fun() -> acceptor(L) end || _ <- lists:seq(1,100)],
    listen_loop(L).

acceptor(L) ->
    Sock = accept(L),
    spawn(fun() -> acceptor(L) end),
    handle_sock(Sock).

The notion of spawning the next acceptor from the
previous acceptor may have to be modified or extended
if you need supervision of the processes, of course.

BR,
Ulf W

-- 
Ulf Wiger
CTO, Erlang Training & Consulting Ltd
http://www.erlang-consulting.com



More information about the erlang-questions mailing list