C11 atomics in C
stdatomic gives you a counter that needs no lock at all.
#include <stdatomic.h>
#include <stdio.h>
static atomic_long hits = 0;
static atomic_flag busy = ATOMIC_FLAG_INIT;
void record(void) {
long previous = atomic_fetch_add(&hits, 1);
(void) previous;
}
long read_hits(void) {
return atomic_load(&hits);
}
int try_enter(void) {
return !atomic_flag_test_and_set(&busy);
}
void leave(void) {
atomic_flag_clear(&busy);
}
How it works
atomic_intis incremented indivisibly.atomic_fetch_addreturns the value from before the add.- Atomics suit counters and flags, not multi-field invariants.
Keywords and builtins used here
atomic_longintleavelongread_hitsrecordreturnstatictry_entervoid
The run, in numbers
- Lines
- 22
- Characters to type
- 366
- Tokens
- 83
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 47 seconds.
Step 1 of 2 in Lock-free & local, step 8 of 10 in Threads & concurrency.