1 #include <stdatomic.h>
2 #include <inttypes.h>
3 #include <stdio.h>
4 
5 #ifdef __GCC_HAVE_SYNC_COMPARE_AND_SWAP_4
6 _Atomic uint32_t    atomic_4;
7 #endif
8 #ifdef __GCC_HAVE_SYNC_COMPARE_AND_SWAP_2
9 _Atomic uint16_t    atomic_2;
10 #endif
11 
12 int
main(void)13 main(void)
14 {
15     int ret = 0;
16 #ifdef __GCC_HAVE_SYNC_COMPARE_AND_SWAP_4
17     uint32_t    zero_4 = 0;
18     if (atomic_compare_exchange_strong(&atomic_4, &zero_4, 1)) {
19         printf("atomic_compare_exchange 4 worked, value %" PRIu32 " zero %" PRIu32 "\n",
20                atomic_4, zero_4);
21         uint32_t        old;
22         old = atomic_exchange_explicit(&atomic_4, 0, memory_order_relaxed);
23         if (atomic_4 == 0 && old == 1) {
24             printf("atomic_exchange_explicit 4 worked %" PRIu32 " value now %" PRIu32 "\n",
25                    old, atomic_4);
26         } else {
27             printf("atomic_exchange_explicit failed %" PRIu32 " value now %" PRIu32 "\n",
28                    old, atomic_4);
29             ret = 1;
30         }
31     } else {
32         printf("atomic_compare_exchange 4 failed, value %" PRIu32 "\n", atomic_4);
33         ret = 1;
34     }
35 #endif
36 #ifdef __GCC_HAVE_SYNC_COMPARE_AND_SWAP_2
37     uint16_t zero_2 = 0;
38     if (atomic_compare_exchange_strong(&atomic_2, &zero_2, 1)) {
39         printf("atomic_compare_exchange 2 worked, value %" PRIu16 " zero %" PRIu16 "\n", atomic_2, zero_2);
40         uint16_t        old;
41         old = atomic_exchange_explicit(&atomic_2, 0, memory_order_relaxed);
42         if (atomic_2 == 0 && old == 1) {
43             printf("atomic_exchange_explicit 2 worked %" PRIu16 " value now %" PRIu16 "\n",
44                    old, atomic_2);
45         } else {
46             printf("atomic_exchange_explicit 2 failed %" PRIu16 " value now %" PRIu16 "\n",
47                    old, atomic_2);
48             ret = 1;
49         }
50     } else {
51         printf("atomic_compare_exchange 2 failed, value %" PRIu16 "\n", atomic_2);
52         ret = 1;
53     }
54 #endif
55     return ret;
56 }
57