CKTIS / C
asynchrony and concurrency — concept C23
C concurrency uses threads, mutexes, condition variables, and atomic objects, while asynchronous signal handlers have a much narrower set of permitted operations. A data race occurs when two conflicting actions are performed by different threads, at least one is non-atomic, and neither happens before the other; the behavior is undefined. `volatile` replaces neither atomics nor a lock.
Version: C23
Syntax
asynchrony and concurrencyC concurrency uses threads, mutexes, condition variables, and atomic objects, while asynchronous signal handlers have a much narrower set of permitted operations. A data race occurs when two conflicting actions are performed by different threads, at least one is non-atomic, and neither happens before the other; the behavior is undefined. volatile replaces neither atomics nor a lock.
A common application is a work queue: a mutex protects its structure, a condition variable sleeps the consumer, and an atomic counter can collect statistics without that lock. Recheck the predicate in a loop after cnd_wait, because waking does not prove a job remains available.
For atomics, choose a memory order that establishes the required data-publication relation; default memory_order_seq_cst is strongest but does not repair non-atomic races. In a signal handler, restrict work to operations permitted by C and volatile sig_atomic_t; locking or ordinary I/O can be unsafe.
A counting semaphore models a pool of permits: a successful acquire consumes one, release returns one, and the permit count invariant for a fixed-capacity pool is 0 <= permits <= capacity; an acquire blocks at zero. A sequential event dispatch simulation processes an ordered queue one event at a time, providing deterministic simulation rather than parallel execution. A masking and preemption simulation must explicitly preserve the mask, interruption point, and task state. With non-preemptive priority scheduling, the highest-priority ready task is chosen only at yield or completion, so one long low-priority step can delay urgent work.
Examples
#include <stdatomic.h>
#include <stdio.h>
int main(void) {
_Atomic int jobs = 1;
atomic_fetch_add(&jobs, 2);
printf("%d\n", atomic_load(&jobs));
return 0;
}
Result
3
C concurrency uses threads, mutexes, condition variables, and atomic objects, while asynchronous signal handlers have a much narrower set of permitted operations. A data race occurs when two conflicting actions are performed by different threads, at least one is non-atomic, and neither happens before the other; the behavior is undefined. `volatile` replaces neither atomics nor a lock.