#include <stdio.h>
#include <threads.h>
#include <stdatomic.h>
atomic_int acnt;
int cnt;
int f(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;
}
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);
printf("The atomic counter is %u\n", acnt
); printf("The non-atomic counter is %u\n", cnt
); }
I2luY2x1ZGUgPHN0ZGlvLmg+CiNpbmNsdWRlIDx0aHJlYWRzLmg+CiNpbmNsdWRlIDxzdGRhdG9taWMuaD4KIAphdG9taWNfaW50IGFjbnQ7CmludCBjbnQ7CiAKaW50IGYodm9pZCAqdGhyX2RhdGEpCnsKICAgIGZvcihpbnQgbiA9IDA7IG4gPCAxMDAwOyArK24pIHsKICAgICAgICArK2NudDsKICAgICAgICArK2FjbnQ7CiAgICAgICAgLy8gZm9yIHRoaXMgZXhhbXBsZSwgcmVsYXhlZCBtZW1vcnkgb3JkZXIgaXMgc3VmZmljaWVudCwgZS5nLgogICAgICAgIC8vIGF0b21pY19mZXRjaF9hZGRfZXhwbGljaXQoJmFjbnQsIDEsIG1lbW9yeV9vcmRlcl9yZWxheGVkKTsKICAgIH0KICAgIHJldHVybiAwOwp9CiAKaW50IG1haW4odm9pZCkKewogICAgdGhyZF90IHRoclsxMF07CiAgICBmb3IoaW50IG4gPSAwOyBuIDwgMTA7ICsrbikKICAgICAgICB0aHJkX2NyZWF0ZSgmdGhyW25dLCBmLCBOVUxMKTsKICAgIGZvcihpbnQgbiA9IDA7IG4gPCAxMDsgKytuKQogICAgICAgIHRocmRfam9pbih0aHJbbl0sIE5VTEwpOwogCiAgICBwcmludGYoIlRoZSBhdG9taWMgY291bnRlciBpcyAldVxuIiwgYWNudCk7CiAgICBwcmludGYoIlRoZSBub24tYXRvbWljIGNvdW50ZXIgaXMgJXVcbiIsIGNudCk7Cn0=