Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

ref.h 2.4KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /* Copyright (c) 2014, Vsevolod Stakhov
  2. * All rights reserved.
  3. *
  4. * Redistribution and use in source and binary forms, with or without
  5. * modification, are permitted provided that the following conditions are met:
  6. * * Redistributions of source code must retain the above copyright
  7. * notice, this list of conditions and the following disclaimer.
  8. * * Redistributions in binary form must reproduce the above copyright
  9. * notice, this list of conditions and the following disclaimer in the
  10. * documentation and/or other materials provided with the distribution.
  11. *
  12. * THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY
  13. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  14. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  15. * DISCLAIMED. IN NO EVENT SHALL AUTHOR BE LIABLE FOR ANY
  16. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  17. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  18. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  19. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  20. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  21. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  22. */
  23. #ifndef REF_H_
  24. #define REF_H_
  25. /**
  26. * @file ref.h
  27. * A set of macros to handle refcounts
  28. */
  29. typedef void (*ref_dtor_cb_t)(void *data);
  30. typedef struct ref_entry_s {
  31. unsigned int refcount;
  32. ref_dtor_cb_t dtor;
  33. } ref_entry_t;
  34. #define REF_INIT(obj, dtor_cb) do { \
  35. (obj)->ref.refcount = 0; \
  36. (obj)->ref.dtor = (ref_dtor_cb_t)(dtor_cb); \
  37. } while (0)
  38. #define REF_INIT_RETAIN(obj, dtor_cb) do { \
  39. (obj)->ref.refcount = 1; \
  40. (obj)->ref.dtor = (ref_dtor_cb_t)(dtor_cb); \
  41. } while (0)
  42. #ifdef HAVE_ATOMIC_BUILTINS
  43. #define REF_RETAIN(obj) do { \
  44. __sync_add_and_fetch (&(obj)->ref.refcount, 1); \
  45. } while (0)
  46. #define REF_RELEASE(obj) do { \
  47. unsigned int rc = __sync_sub_and_fetch (&(obj)->ref.refcount, 1); \
  48. if (rc == 0 && (obj)->ref.dtor) { \
  49. (obj)->ref.dtor (obj); \
  50. } \
  51. } while (0)
  52. #else
  53. #define REF_RETAIN(obj) do { \
  54. (obj)->ref.refcount ++; \
  55. } while (0)
  56. #define REF_RELEASE(obj) do { \
  57. if (--(obj)->ref.refcount == 0 && (obj)->ref.dtor) { \
  58. (obj)->ref.dtor (obj); \
  59. } \
  60. } while (0)
  61. #endif
  62. #endif /* REF_H_ */