Zurück zur SP2 Übersicht
atomic.c
#include <stdatomic.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <pthread.h>
#ifdef __STDC_NO_ATOMICS__
#error No support for C11 Atomics
#endif
static _Atomic long foo = ATOMIC_VAR_INIT(0);
static long bar = 0;
static void *counter(void *arg) {
for (long i = 0; i < 10000000; ++i) {
bar++;
}
for (long i = 0; i < 10000000; ++i) {
atomic_fetch_add(&foo, 1);
}
return NULL;
}
int main(void) {
int threads = 10;
pthread_t tids[threads];
for (int i = 0; i < threads; ++i) {
pthread_create(&tids[i], NULL, counter, NULL);
}
for (int i = 0; i < threads; ++i) {
void *bla;
pthread_join(tids[i], &bla);
}
printf("foo = %zu\n", foo);
printf("bar = %zu\n", bar);
return EXIT_SUCCESS;
}