C语言引用计数

 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 }
原文地址:https://www.cnblogs.com/wenqiang/p/15398667.html