Reputation: 21
i.e.
Upvotes: 2
Views: 3990
Reputation: 2765
Yes you can but your example is a little incomplete:
epoll_wait makes sures that only one thread gets the connection event and only that thread will call accept.
If you create two epoll sets and register your listening_socket to both of them you will receive the event twice, once per epoll set, and this is not recommended.
You may refer to this tutorial http://www.devshed.com/c/a/BrainDump/Linux-Files-and-the-Event-Poll-Interface/ and search some interesting discussions about epoll in this forum http://www.developerweb.net/forum/ to learn more.
For more elaborate examples you can always refer to the libev, libevent or nginx source code.
Upvotes: 4
Reputation: 27900
In general, it's not a good idea to have multiple threads performing IO on the same socket without some kind of synchronization between them. In your scenario, it's possible you'd see something like:
accept
, 1 call succeeds, N-1 block (or fail, if your listening socket is non-blocking)The more usual approach is to have the parent thread loop calling accept
on the listening socket, and starting a child thread for each incoming request. (Or, if you're concerned about thread creation overhead, you can have a pool of child threads that wait on a condition variable when idle; the parent adds the newly-accepted socket to a queue and uses pthread_cond_signal
to wake a child to handle it.)
Upvotes: 5