Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 621
alkedr Avatar asked Jul 15 '12 00:07

alkedr


People also ask

Can multiple threads use the same socket?

No two threads can use the same Socket because of the Synchronize sections. So they're never mutating it at the same time.

Why multithreading is important in socket Programming?

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.

Is send and recv thread safe?

send and recv are thread-safe.

What is threading in socket Programming?

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.


1 Answers

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.

like image 86
Duck Avatar answered Nov 09 '22 05:11

Duck