linux-sysprog · beginner · ~15 min
The accumulate-then-clear semantics of eventfd.
eventfd holds a 64-bit counter. Each write(fd, &n, 8) ADDS n. Each
read(fd, &out, 8) returns the current counter AND resets it to 0.
Implement these two operations on a simulated counter:
unsigned long long evfd_write(unsigned long long *counter, unsigned long long n);
unsigned long long evfd_read (unsigned long long *counter);
evfd_write adds n and returns the new counter value.evfd_read returns the current counter value and resets the counter to 0.eventfd is the simplest thread-wakeup primitive on Linux. Understanding its accumulate-then-clear semantics builds the muscle for using it correctly.
Counter pointer + (for write) increment.
New counter value (write) or pre-read value (read).
No syscalls; pure simulation.
#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.