Skip to content

eventfd

eventfd provides a lightweight file-descriptor-based event counter. It is useful when one execution context needs to notify another through an fd that can be monitored by poll() or epoll().

Core Concept

producer writes uint64_t value
eventfd counter increases
eventfd becomes readable
consumer reads uint64_t value
event consumed

Common Use Cases

  • Thread-to-thread notification
  • Kernel-to-userspace notification
  • Waking an epoll loop from another context
  • Bridging signal-style events into fd-based event loops
  • Notifying userspace that shared memory contains new data

Basic Usage

int efd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);

Notify:

uint64_t value = 1;
write(efd, &value, sizeof(value));

Consume:

uint64_t value;
read(efd, &value, sizeof(value));

Important Behavior

  • The eventfd counter is 64-bit.
  • write() adds to the counter.
  • read() consumes the counter value.
  • In normal mode, one read returns the current counter and resets it to zero.
  • In semaphore mode, each read returns 1 and decrements the counter by one.

eventfd vs pipe

Item eventfd pipe
Data model 64-bit counter byte stream
Best for notifications data transfer
epoll integration yes yes
Overhead low higher

Common Pitfalls

Pitfall Result
Treating eventfd as a data channel Only a counter is transferred
Forgetting to read it epoll keeps reporting it as readable
Writing the wrong size write() must use 8 bytes
Reading the wrong size read() must use 8 bytes