I am using Linux 3.2.0, x86_64. Can I call accept() for one socket from several threads simultaneously?
No two threads can use the same Socket because of the Synchronize sections. So they're never mutating it at the same time.
Using threads you can be handling two different connections on the server at the same time. Otherwise you'll have to handle them sequentially. Imagine a webserver that can only serve one http request at a time. Using treading the webserver will be able to handle more requests in parallel.
send and recv are thread-safe.
A thread is a sequence of instructions that run independently of the program and of any other threads. Using threads, a multi-threaded server program can accept a connection from a client, start a thread for that communication, and continue listening for requests from other clients.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With