]> git.lizzy.rs Git - dragonstd.git/blob - refcount.c
Merge branch 'main' of https://github.com/dragonblocks/dragonstd
[dragonstd.git] / refcount.c
1 #include "refcount.h"
2
3 void refcount_ini(Refcount *refcount, void *obj, Callback del)
4 {
5         refcount->obj = obj;
6         refcount->del = del;
7         refcount->cnt = 1;
8         pthread_mutex_init(&refcount->mtx, NULL);
9 }
10
11 void refcount_dst(Refcount *refcount)
12 {
13         pthread_mutex_destroy(&refcount->mtx);
14 }
15
16 void *refcount_inc(void *refcount)
17 {
18         Refcount *rc = refcount;
19
20         pthread_mutex_lock(&rc->mtx);
21         rc->cnt++;
22         pthread_mutex_unlock(&rc->mtx);
23         return rc;
24 }
25
26 void *refcount_grb(void *refcount)
27 {
28         return refcount_obj(refcount_inc(refcount));
29 }
30
31 void refcount_drp(void *refcount)
32 {
33         Refcount *rc = refcount;
34
35         pthread_mutex_lock(&rc->mtx);
36         unsigned short count = --rc->cnt;
37         pthread_mutex_unlock(&rc->mtx);
38
39         if (!count)
40                 rc->del(rc->obj);
41 }
42
43 void *refcount_obj(void *refcount)
44 {
45         return ((Refcount *) refcount)->obj;
46 }