linux-sysprog · beginner · ~15 min
The accumulate-then-clear semantics of eventfd.
Model the accumulate-then-clear behaviour of a Linux eventfd as two functions on a plain 64-bit counter. This is a pure simulation — no real eventfd or syscalls are involved.
Implement the two operations that mirror an eventfd: writing adds to the counter; reading drains it.
unsigned long long evfd_write(unsigned long long *counter, unsigned long long n);
unsigned long long evfd_read (unsigned long long *counter);
counter: pointer to the shared counter (the simulated eventfd's internal value).n (write only): the amount to add.evfd_write adds n to *counter and returns the new value.evfd_read returns the current value of *counter and then resets *counter to 0.c = 0
evfd_write(&c, 5) -> 5 (c == 5)
evfd_write(&c, 3) -> 8 (c == 8)
evfd_read(&c) -> 8 (c reset to 0)
evfd_read(&c) -> 0 (c stays 0)
eventfd is the simplest thread-wakeup primitive on Linux. Understanding its accumulate-then-clear semantics builds the muscle for using it correctly.
A pointer to the 64-bit counter, plus (for write) the amount n to add.
evfd_write returns the new counter value; evfd_read returns the value before clearing and resets the counter to 0.
Reading drains the counter to 0. Pure simulation — no syscalls.
#include <stddef.h>
unsigned long long evfd_write(unsigned long long *counter, unsigned long long n) { /* TODO */ return 0; }
unsigned long long evfd_read (unsigned long long *counter) { /* TODO */ return 0; }
Forgetting that read RESETS the counter, not just observes.
Read with counter at 0; multiple writes between reads.
O(1).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.