9

I am using Linux 3.2.0, x86_64. Can I call accept() for one socket from several threads simultaneously?

1

1 Answer 1

13

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.

12
  • 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.
    – alkedr
    Jul 15, 2012 at 0:52
  • If you say so. Just keep in mind there are reasons why best practices emerge.
    – Duck
    Jul 15, 2012 at 1:09
  • 1
    What are these reasons? Why are two queues better than one?
    – alkedr
    Jul 15, 2012 at 1:12
  • 1
    backlog 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.
    – Duck
    Jul 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 if accept still has this issue anymore, though.
    – jxh
    Jul 15, 2012 at 1:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.