]> git.lizzy.rs Git - dragonstd.git/blob - refcount.h
Use void pointers for callback args
[dragonstd.git] / refcount.h
1 /*
2         Refcount
3         --------
4
5         An object that knows how and when to delete itself, using a reference counter.
6
7         Whenever a reference to an object like this is obtained/kept, it needs to be grabbed,
8                 whenever a reference is discarded, it needs to be dropped.
9
10         Made for use with the List/Tree/Map types: refcount_inc, refcount_grb, refcount_drp
11                 can be used as add, get, del callbacks.
12 */
13 #ifndef _DRAGONSTD_REFCOUNT_H_ // include guard
14 #define _DRAGONSTD_REFCOUNT_H_
15
16 #include <pthread.h>       // for pthread_mutex_t
17
18 typedef struct {
19         /* private */
20         void *obj;
21         void *del;
22         unsigned short cnt;  // counter
23         pthread_mutex_t mtx; // lock to protect count
24 } Refcount;
25
26 void refcount_ini(Refcount *refcount, void *obj, void *del);
27 /*
28         Initializes the refcount.
29
30         The refcount should be uninitialized or deleted before passed to this function.
31         This function should be called before any other function is called on the refcount.
32 */
33
34 void refcount_dst(Refcount *refcount);
35 /*
36         Destroy the refcount.
37
38         This does NOT mean delete the object that the reference counter is referring to-
39         This means delete the refcount structure itself (and is usually called from the
40         delete callback of the referenced object).
41
42         The refcount is unusable until reinitialized afterwards.
43 */
44
45 void *refcount_inc(Refcount *refcount);
46 /*
47         [Thread Safe]
48         Grab a reference to the refcount.
49
50         Returns the refcount.
51 */
52
53 void *refcount_grb(Refcount *rc);
54 /*
55         [Thread Safe]
56         Does the same as refcount_inc, except it returns the referenced object instead of the
57                 refcount.
58 */
59
60 void refcount_drp(Refcount *refcount);
61 /*
62         [Thread Safe]
63         Drop a reference to the object.
64
65         May delete the object using the del function if the counter gets down to zero.
66 */
67
68 void *refcount_obj(Refcount *refcount);
69 /*
70         [Thread Safe]
71         Return referenced object.
72 */
73
74 #endif // _DRAGONSTD_REFCOUNT_H_