thodg
thodg

Reputation: 1767

Why dup(2) listening sockets in multiple threaded servers?

I know programmers are often not so easy with threads and parallel programming, so this is a question for experts on the matter in priority.

There seems to be a relatively accepted but unknown good practice of calling dup(2) on listening sockets for threaded server applications. I understand the general principle of "share nothing" threads for peace of mind avoiding race conditions.

My question is : if the kernel already does mutual exclusion on accept(2) return values, exactly why is it interesting at all to dup(2) the listening socket ?

In case it is really an improvement, when should the socket be dup(2)-ed : after bind(2) or after listen(2) ?

Upvotes: 2

Views: 766

Answers (1)

Jean-Baptiste Yunès
Jean-Baptiste Yunès

Reputation: 36391

Yes kernel ensure that only one process/thread will be served in concurrent calls to accept. If you want do use it correctly, then you need to do it after bind and listen. After bind because you want to share a bound server socket... After listen to correctly configure the backlog for everybody.

Now it is a matter of design: you may prefer to have a single accepting thread dispatching the work among a pool of other threads (then you need to manage a pool by yourself), or have concurrent accepting threads and put the burden on the system. The first is more complex to set up but let you have a finer control on balancing. The second is much more straightforward but doesn't give you any control on the balancing.

Upvotes: 3

Related Questions