linux-sysprog · beginner · ~15 min

Simulate an eventfd counter

The accumulate-then-clear semantics of eventfd.

Challenge

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.

Task

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

Input

  • counter: pointer to the shared counter (the simulated eventfd's internal value).
  • n (write only): the amount to add.

Output

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

Example

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)

Edge cases

  • Reading when the counter is 0 returns 0.
  • Multiple writes between reads accumulate.

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

A pointer to the 64-bit counter, plus (for write) the amount n to add.

Output format

evfd_write returns the new counter value; evfd_read returns the value before clearing and resets the counter to 0.

Constraints

Reading drains the counter to 0. Pure simulation — no syscalls.

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.