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