I am creating a multithreaded server using epoll (edge-triggered) and non-blocking sockets. Currently I'm creating an event loop on the main thread and waiting for notifications and it works correctly
I have to choose between two approaches to make it multithreaded:
If I use the first method, is there a chance for multiple threads to get notified with the same event? how can I handle this situation?
What could be the best approach? Thank you.
Yes, epoll is thread-safe. Yes, you can do it.
epoll_ctl with EPOLL_CTL_ADD should be called once for each socket. And when epoll_wait is called, it will monitor all the sockets that are added and return only those FDs that have some events to consume.
epoll is a Linux kernel system call for a scalable I/O event notification mechanism, first introduced in version 2.5. 44 of the Linux kernel. Its function is to monitor multiple file descriptors to see whether I/O is possible on any of them.
I think option 1 is more popular since the primary purpose of non-blocking IO is to avoid the overhead of create & destroy threads.
take the popular web server nginx as an example, it create multiple processes (not threads) to handle incoming events on a handle, and the process the events in the subprocess. all of them share the same listening socket. it's quite similar to option 1.
I'm also writing a server using epoll
, and I have considered the same model as you attached.
It is possible to use option 1, but it may cause "thundering herd" effect, you can read the source of nginx to find the solution. As for option 2, I deem that it is better to use thread pool instead of spawning a new thread each time.
And you can also the following model:
Main thread/process: accept
incoming connection with blocking IO, and send the fd to the other threads using BlockingList or to the other processes using PIPE
.
Sub threads/process: create an instance of epoll
respectively, and add the incoming fd to the epoll
, then processing them with non-blocking IO.
an event loop for each thread is the most flexible with high performance You should create an epoll fd for each event loop, there is no concern about epoll thread-safe problem.
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