linuxmultithreadingsocketspthreadsposix

Can I call accept() for one socket from several threads simultaneously?


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


Solution

  • 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.