ref.h 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. * Copyright (c) 2006-2023, RT-Thread Development Team
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. *
  6. * Change Logs:
  7. * Date Author Notes
  8. * 2022-3-1 zhouxiaohu first version
  9. * 2023-5-18 GuEe-GUI implemented by rtatomic
  10. */
  11. #ifndef __UTIL_REF_H__
  12. #define __UTIL_REF_H__
  13. #include <rtatomic.h>
  14. /**
  15. * struct ref must be embedded in an object.
  16. * it acts as a reference counter for the object.
  17. */
  18. struct rt_ref
  19. {
  20. rt_atomic_t refcount;
  21. };
  22. #define RT_REF_INIT(n) { .refcount = n, }
  23. rt_inline void rt_ref_init(struct rt_ref *r)
  24. {
  25. rt_atomic_store(&r->refcount, 1);
  26. }
  27. rt_inline unsigned int rt_ref_read(struct rt_ref *r)
  28. {
  29. return rt_atomic_load(&r->refcount);
  30. }
  31. /**
  32. * ref_get
  33. * increment reference counter for object.
  34. */
  35. rt_inline void rt_ref_get(struct rt_ref *r)
  36. {
  37. rt_atomic_add(&r->refcount, 1);
  38. }
  39. /**
  40. * ref_put
  41. * decrement reference counter for object.
  42. * If the reference counter is zero, call release().
  43. *
  44. * Return 1 means the object's reference counter is zero and release() is called.
  45. */
  46. rt_inline int rt_ref_put(struct rt_ref *r, void (*release)(struct rt_ref *r))
  47. {
  48. if (rt_atomic_dec_and_test(&r->refcount))
  49. {
  50. release(r);
  51. return 1;
  52. }
  53. return 0;
  54. }
  55. /**
  56. * ref_get_unless_zero - Increment refcount for object unless it is zero.
  57. * Return non-zero if the increment succeeded. Otherwise return 0.
  58. */
  59. rt_inline int rt_ref_get_unless_zero(struct rt_ref *r)
  60. {
  61. return (int)rt_atomic_inc_not_zero(&r->refcount);
  62. }
  63. #endif /* __UTIL_REF_H__ */