bungeman@google.com | d9947f6 | 2013-12-18 15:27:39 +0000 | [diff] [blame^] | 1 | /* |
| 2 | * Copyright 2013 Google Inc. |
| 3 | * |
| 4 | * Use of this source code is governed by a BSD-style license that can be |
| 5 | * found in the LICENSE file. |
| 6 | */ |
| 7 | |
| 8 | #ifndef SkAtomics_sync_DEFINED |
| 9 | #define SkAtomics_sync_DEFINED |
| 10 | |
| 11 | /** GCC/Clang __sync based atomics. */ |
| 12 | |
| 13 | #include <stdint.h> |
| 14 | |
| 15 | static inline __attribute__((always_inline)) int32_t sk_atomic_inc(int32_t* addr) { |
| 16 | return __sync_fetch_and_add(addr, 1); |
| 17 | } |
| 18 | |
| 19 | static inline __attribute__((always_inline)) int32_t sk_atomic_add(int32_t* addr, int32_t inc) { |
| 20 | return __sync_fetch_and_add(addr, inc); |
| 21 | } |
| 22 | |
| 23 | static inline __attribute__((always_inline)) int32_t sk_atomic_dec(int32_t* addr) { |
| 24 | return __sync_fetch_and_add(addr, -1); |
| 25 | } |
| 26 | |
| 27 | static inline __attribute__((always_inline)) void sk_membar_acquire__after_atomic_dec() { } |
| 28 | |
| 29 | static inline __attribute__((always_inline)) int32_t sk_atomic_conditional_inc(int32_t* addr) { |
| 30 | int32_t value = *addr; |
| 31 | |
| 32 | while (true) { |
| 33 | if (value == 0) { |
| 34 | return 0; |
| 35 | } |
| 36 | |
| 37 | int32_t before = __sync_val_compare_and_swap(addr, value, value + 1); |
| 38 | |
| 39 | if (before == value) { |
| 40 | return value; |
| 41 | } else { |
| 42 | value = before; |
| 43 | } |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | static inline __attribute__((always_inline)) void sk_membar_acquire__after_atomic_conditional_inc() { } |
| 48 | |
| 49 | #endif |