Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is epoll thread-safe?

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?

like image 280
atomd Avatar asked Aug 14 '11 18:08

atomd


People also ask

Is epoll multithreaded?

Yes, epoll is thread-safe. Yes, you can do it.

Is write Syscall thread-safe?

write() is certainly thread-safe. The problem is that a partial write() could require multiple calls in order to completely write the data, and while that is "thread-safe" it could result in interleaved data.

What is epoll in Linux?

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.


2 Answers

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.)

like image 110
cmeerw Avatar answered Sep 30 '22 11:09

cmeerw


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.

like image 44
VL-80 Avatar answered Sep 30 '22 10:09

VL-80