typestar

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

  1. atomic_int is incremented indivisibly.
  2. atomic_fetch_add returns the value from before the add.
  3. Atomics suit counters and flags, not multi-field invariants.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 2 in Lock-free & local, step 8 of 10 in Threads & concurrency.

← Previous Next →