b3a1dcfd3fa08cfc20c9a4abb25188fc9db47e6a
[mono.git] / mono / utils / refcount.h
1
2 #ifndef __MONO_UTILS_REFCOUNT_H__
3 #define __MONO_UTILS_REFCOUNT_H__
4
5 #include <glib.h>
6 #include <config.h>
7
8 #include "atomic.h"
9
10 /*
11  * Mechanism for ref-counting which tries to be as user-friendly as possible. Instead of being a wrapper around
12  * user-provided data, it is embedded into the user data.
13  *
14  * This introduces some constraints on the MonoRefCount field:
15  *  - it needs to be called "ref"
16  *  - it cannot be a pointer
17  */
18
19 typedef struct {
20         guint32 ref;
21         void (*destructor) (gpointer data);
22 } MonoRefCount;
23
24 #define mono_refcount_init(v,destructor) do { mono_refcount_initialize (&(v)->ref, (destructor)); } while (0)
25 #define mono_refcount_inc(v) (mono_refcount_increment (&(v)->ref),(v))
26 #define mono_refcount_dec(v) do { mono_refcount_decrement (&(v)->ref); } while (0)
27
28 static inline void
29 mono_refcount_initialize (MonoRefCount *refcount, void (*destructor) (gpointer data))
30 {
31         refcount->ref = 1;
32         refcount->destructor = destructor;
33 }
34
35 static inline void
36 mono_refcount_increment (MonoRefCount *refcount)
37 {
38         guint32 oldref, newref;
39
40         g_assert (refcount);
41
42         do {
43                 oldref = refcount->ref;
44                 if (oldref == 0)
45                         g_error ("%s: cannot increment a ref with value 0", __func__);
46
47                 newref = oldref + 1;
48         } while (InterlockedCompareExchange ((gint32*) &refcount->ref, newref, oldref) != oldref);
49 }
50
51 static inline void
52 mono_refcount_decrement (MonoRefCount *refcount)
53 {
54         guint32 oldref, newref;
55
56         g_assert (refcount);
57
58         do {
59                 oldref = refcount->ref;
60                 if (oldref == 0)
61                         g_error ("%s: cannot decrement a ref with value 0", __func__);
62
63                 newref = oldref - 1;
64         } while (InterlockedCompareExchange ((gint32*) &refcount->ref, newref, oldref) != oldref);
65
66         if (newref == 0 && refcount->destructor)
67                 refcount->destructor ((gpointer) refcount);
68 }
69
70 #endif /* __MONO_UTILS_REFCOUNT_H__ */