[sheepdog] [PATCH 2/8] util: introduce a new data type refcnt_t for reference counting

Hitoshi Mitake mitake.hitoshi at lab.ntt.co.jp
Tue Jul 9 04:36:36 CEST 2013


From: Hitoshi Mitake <mitake.hitoshi at gmail.com>

Using raw int for reference counting directly is dangerous because it
cannot detect ++ or -- for these counters at compilation time. So this
patch implements a new data type refcnt_t for safe reference counting
which can be done by multiple threads in parallel.

Signed-off-by: Hitoshi Mitake <mitake.hitoshi at lab.ntt.co.jp>
---
 include/util.h |   39 +++++++++++++++++++++++++++++++++++++++
 1 file changed, 39 insertions(+)

diff --git a/include/util.h b/include/util.h
index ce5ce07..6535164 100644
--- a/include/util.h
+++ b/include/util.h
@@ -212,6 +212,45 @@ static inline void uatomic_set_false(uatomic_bool *val)
 	(typeof(*(p)))ret;				\
 })
 
+/*
+ * refcnt_t: reference counter which can be accessed by multiple threads safely
+ *
+ * If you only want to use reference counters which are only incremented or
+ * decremented by a main thread (caller of event_loop()), use main_refcnt_t
+ * (defined in work.h).
+ */
+
+typedef struct {
+	int val;
+} refcnt_t;
+
+static inline int refcnt_read(refcnt_t *rc)
+{
+	return rc->val;
+}
+
+static inline void refcnt_set(refcnt_t *rc, int val)
+{
+	rc->val = val;
+}
+
+static inline void refcnt_inc(refcnt_t *rc)
+{
+	uatomic_inc(&rc->val);
+}
+
+static inline void refcnt_dec(refcnt_t *rc)
+{
+	uatomic_dec(&rc->val);
+	assert(0 <= rc->val);
+}
+
+static inline int refcnt_dec_return(refcnt_t *rc)
+{
+	refcnt_dec(rc);
+	return refcnt_read(rc);
+}
+
 /* colors */
 #define TEXT_NORMAL         "\033[0m"
 #define TEXT_BOLD           "\033[1m"
-- 
1.7.10.4




More information about the sheepdog mailing list