38

There are two functions in epoll:

  1. epoll_ctl
  2. epoll_wait

Are they thread-safe when I use the same epoll_fd?
What will happen if one thread calls epoll_wait and others call epoll_ctl at the same time?

atomd
  • 558
  • 1
  • 5
  • 11
  • 1
    do you use the same epoll_fd ? – Karoly Horvath Aug 14 '11 at 18:19
  • yes, I use the same epoll_fd. – atomd Aug 14 '11 at 18:20
  • Can you give more details about your usage? Why do you have to use the same epoll fd? If you are doing an RX/TX structure, you can have one epoll fd corrsepond to the IN events and one correspond to the out events (this is what I use in a few apps) – Foo Bah Aug 14 '11 at 18:40
  • Hi, I use epll io multiplexing with the thread pool, and I want to use epoll_ctl to change the events on other threads. But I do not know whether I need to use some synchronization mechanism to ensure thread safety. – atomd Aug 15 '11 at 01:17

2 Answers2

26

It is thread-safe, but there isn't much documentation that explicitly states that. See here

BTW, you can also have multiple threads waiting on a single epoll_fd, but in that case it can get a bit tricky. (I.e. you might want to use edge-triggered EPOLLET or oneshot mode EPOLLONESHOT. See here.)

Olivia Stork
  • 4,660
  • 5
  • 27
  • 40
cmeerw
  • 7,176
  • 33
  • 27
4

Note: The existing accepted answer is correct, but it mentions "there isn't much documentation that explicitly states that", while epoll documentation does state it.

The manual page for epoll_wait explicitly allows adding a file descriptor to an epoll set while it is being waited for in another thread:

Section "Notes":

While one thread is blocked in a call to epoll_wait(), it is possible for another thread to add a file descriptor to the waited-upon epoll instance. If the new file descriptor becomes ready, it will cause the epoll_wait() call to unblock.

VL-80
  • 517
  • 13
  • 29