1 struct ref {
 2     void (*free)(const struct ref *);
 3     int count;
 4 };
 5 
 6 static inline void
 7 ref_inc(const struct ref *ref)
 8 {
 9     ((struct ref *)ref)->count++;
10 }
11 
12 static inline void
13 ref_dec(const struct ref *ref)
14 {
15     if (--((struct ref *)ref)->count == 0)
16         ref->free(ref);
17 }

线程安全:

 1 static inline void
 2 ref_inc(const struct ref *ref)
 3 {
 4     __sync_add_and_fetch((int *)&ref->count, 1);
 5 }
 6 
 7 static inline void
 8 ref_dec(const struct ref *ref)
 9 {
10     if (__sync_sub_and_fetch((int *)&ref->count, 1) == 0)
11         ref->free(ref);
12 }

 

相关文章:

  • 2021-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-21
  • 2022-12-23
  • 2022-02-05
猜你喜欢
  • 2022-12-23
  • 2021-09-06
  • 2022-02-15
  • 2021-05-16
  • 2022-12-23
  • 2021-12-09
相关资源
相似解决方案