In socket programming, can take () the same listening socket on a multiprocessor (thread)?
In general, it is not recommended to have multiple threads doing IO on the same socket without any kind of synchronization between them. In your script, you might see something like:
- an incoming connection request wakes up epoll_wait on all N child threads.
- all N threads call
accept
, 1 call succeeds, block N-1 (or fail if your listening socket is not blocking)
A more common approach is to loop the parent thread accept
on the listening socket and start the child thread on every incoming request. (Or, if you are worried about the overhead of creating threads, you can have a pool of child threads that wait for a condition variable while waiting, the parent adds the newly accepted socket to the queue and uses it pthread_cond_signal
to wake up the child to process it.)
a source to share
Yes you can, but your example is a little incomplete:
- Create listen_socket
- Create epoll set using epoll_create
- Register listen_socket for epoll set using epoll_ctl
- call epoll_wait ( set epoll ) on child1, child2, child3 ....
- accept the call in each child case if there is a connection request
epoll_wait concludes that only one thread receives the connection event, and only that thread calls accept.
If you create two epoll sets and register your listen_socket for both of them, you will receive the event twice, once per epoll set, and this is not recommended.
You can refer to this tutorial http://www.devshed.com/c/a/BrainDump/Linux-Files-and-the-Event-Poll-Interface/ and find interesting discussions about epoll on this forum http: // www .developerweb.net / forum / for more information.
For more complex examples, you can always refer to the libev, libevent or nginx source code.
a source to share