snipplets.dev/code/C/atomic.c

29 lines
601 B
C
Raw Normal View History

2023-08-01 03:25:33 +03:00
#include <stdio.h>
#include <threads.h>
#include <stdatomic.h>
atomic_int acnt;
int cnt;
2024-04-27 23:54:46 +03:00
int f(void *thr_data) {
(void)thr_data;
for (int n = 0; n < 1000; ++n) {
++cnt;
++acnt;
// for this example, relaxed memory order is sufficient, e.g.
// atomic_fetch_add_explicit(&acnt, 1, memory_order_relaxed);
}
return 0;
2023-08-01 03:25:33 +03:00
}
2024-04-27 23:54:46 +03:00
int main(void) {
thrd_t thr[10];
for (int n = 0; n < 10; ++n)
thrd_create(&thr[n], f, NULL);
for (int n = 0; n < 10; ++n)
thrd_join(thr[n], NULL);
2023-08-01 03:25:33 +03:00
2024-04-27 23:54:46 +03:00
printf("The atomic counter is %u\n", acnt);
printf("The non-atomic counter is %u\n", cnt);
2023-08-01 03:25:33 +03:00
}