linux-sysprog · beginner · ~15 min

Simulate an eventfd counter

The accumulate-then-clear semantics of eventfd.

Challenge

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.

Why this matters

eventfd is the simplest thread-wakeup primitive on Linux. Understanding its accumulate-then-clear semantics builds the muscle for using it correctly.

Input format

Counter pointer + (for write) increment.

Output format

New counter value (write) or pre-read value (read).

Constraints

No syscalls; pure simulation.

Starter code

#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; }

Common mistakes

Forgetting that read RESETS the counter, not just observes.

Edge cases to handle

Read with counter at 0; multiple writes between reads.

Complexity

O(1).

Background lessons

Up next

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.