hatomic.h 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. #ifndef HV_ATOMIC_H_
  2. #define HV_ATOMIC_H_
  3. #ifdef __cplusplus
  4. // c++11
  5. #include <atomic>
  6. #else
  7. #include "hconfig.h" // for HAVE_STDATOMIC_H
  8. #if HAVE_STDATOMIC_H
  9. // c11
  10. #include <stdatomic.h>
  11. #else
  12. #include "hplatform.h" // for bool, size_t
  13. typedef volatile bool atomic_bool;
  14. typedef volatile char atomic_char;
  15. typedef volatile unsigned char atomic_uchar;
  16. typedef volatile short atomic_short;
  17. typedef volatile unsigned short atomic_ushort;
  18. typedef volatile int atomic_int;
  19. typedef volatile unsigned int atomic_uint;
  20. typedef volatile long atomic_long;
  21. typedef volatile unsigned long atomic_ulong;
  22. typedef volatile long long atomic_llong;
  23. typedef volatile unsigned long long atomic_ullong;
  24. typedef volatile size_t atomic_size_t;
  25. typedef struct atomic_flag { atomic_bool _Value; } atomic_flag;
  26. #define ATOMIC_FLAG_INIT { 0 }
  27. #define ATOMIC_VAR_INIT(value) (value)
  28. #ifdef __GNUC__
  29. static inline bool atomic_flag_test_and_set(atomic_flag* p) {
  30. return !__sync_bool_compare_and_swap(&p->_Value, 0, 1);
  31. }
  32. static inline void atomic_flag_clear(atomic_flag* p) {
  33. p->_Value = 0;
  34. }
  35. #define atomic_fetch_add __sync_fetch_and_add
  36. #define atomic_fetch_sub __sync_fetch_add_sub
  37. #else
  38. static inline bool atomic_flag_test_and_set(atomic_flag* p) {
  39. bool ret = p->_Value;
  40. p->_Value = 1;
  41. return ret;
  42. }
  43. static inline void atomic_flag_clear(atomic_flag* p) {
  44. p->_Value = 0;
  45. }
  46. #define atomic_fetch_add(p, n) *(p); *(p) += (n)
  47. #define atomic_fetch_sub(p, n) *(p); *(p) -= (n)
  48. #endif // __GNUC__
  49. #endif // HAVE_STDATOMIC_H
  50. #ifndef ATOMIC_ADD
  51. #define ATOMIC_ADD atomic_fetch_add
  52. #endif
  53. #ifndef ATOMIC_SUB
  54. #define ATOMIC_SUB atomic_fetch_sub
  55. #endif
  56. #ifndef ATOMIC_INC
  57. #define ATOMIC_INC(p) ATOMIC_ADD(p, 1)
  58. #endif
  59. #ifndef ATOMIC_DEC
  60. #define ATOMIC_DEC(p) ATOMIC_SUB(p, 1)
  61. #endif
  62. #endif // __cplusplus
  63. #endif // HV_ATOMIC_H_