atomic variable c

Solutions on MaxInterview for atomic variable c by the best coders in the world

showing results for - "atomic variable c"
Lorenzo
04 Jul 2020
1#include <stdio.h>
2#include <threads.h>
3#include <stdatomic.h>
4
5atomic_int acnt;
6int cnt;
7
8int f(void* thr_data)
9{
10    (void)thr_data;
11    for(int n = 0; n < 1000; ++n) {
12        ++cnt;
13        ++acnt;
14        // for this example, relaxed memory order is sufficient, e.g.
15        // atomic_fetch_add_explicit(&acnt, 1, memory_order_relaxed);
16    }
17    return 0;
18}
19
20int main(void)
21{
22    thrd_t thr[10];
23    for(int n = 0; n < 10; ++n)
24        thrd_create(&thr[n], f, NULL);
25    for(int n = 0; n < 10; ++n)
26        thrd_join(thr[n], NULL);
27
28    printf("The atomic counter is %u\n", acnt);
29    printf("The non-atomic counter is %u\n", cnt);
30}
31