I am using Linux 3.2.0, x86_64. Can I call accept() for one socket from several threads simultaneously?
1 Answer
Yes, you can call accept()
on the same listening socket from multiple threads and multiple process though there might not be as much point to it as you think. The kernel will only allow one to succeed. When this is done with processes it is known as pre-forking and it saves the expense of a fork()
for every new connection. But when you are dealing with threads you can more easily have an existing thread pool that waits on a queue of new connections. One thread does the accept
and writes the queue and the worker threads read the queue and do their thing. It's cleaner, it's a well understood pattern, and you lose almost nothing.
-
From opengroup.org, listen() function: "The backlog argument provides a hint to the implementation which the implementation shall use to limit the number of outstanding connections in the socket's listen queue." There is a queue already, we shouldn't need another.– alkedrJul 15, 2012 at 0:52
-
If you say so. Just keep in mind there are reasons why best practices emerge.– DuckJul 15, 2012 at 1:09
-
1
-
1backlog queue is advisory & you don't have much control w/o being root; it normally isn't very large and tcp starts rejecting connections when it is full. You can control your own queue more easily and accept many more connections and handle them as needed with your various threads and/or multiplexing. If you want to temporarily stop accepting connections you have multiple threads to attempt to reign in not just one. If you want to shut down your threads you may have to start blowing them out while they block on accept rather than cleanly. It makes load balancing harder. Off top of head.– DuckJul 15, 2012 at 1:38
-
Earlier versions of
accept
would serialize access to the system call, but would wake up all threads/processes when it became available, resulting in the thundering herd problem, which a properly implemented secondary queue solves. I am not sure ifaccept
still has this issue anymore, though.– jxhJul 15, 2012 at 1:40