kit

kit
git clone https://git.ryansepassi.com/git/kit.git
Log | Files | Refs | README

builtin_19_atomic_cas_loop.c (522B)


      1 /* Lock-free increment via CAS retry loop. Single-threaded test, so the
      2  * first CAS attempt always succeeds, but the loop shape exercises the
      3  * compare-exchange surface end-to-end. */
      4 int atomic_inc(int* p) {
      5   int cur = __atomic_load_n(p, __ATOMIC_ACQUIRE);
      6   for (;;) {
      7     int next = cur + 1;
      8     if (__atomic_compare_exchange_n(p, &cur, next, 0, __ATOMIC_ACQ_REL,
      9                                     __ATOMIC_ACQUIRE)) {
     10       return next;
     11     }
     12   }
     13 }
     14 
     15 int test_main(void) {
     16   int x = 41;
     17   return atomic_inc(&x);
     18 }