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

Hitoshi Mitake mitake.hitoshi at lab.ntt.co.jp
Thu Jul 11 03:48:11 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>
---
v3:
 - rename the prefix refcnt_ -> refcount_

 include/util.h |   30 ++++++++++++++++++++++++++++++
 1 file changed, 30 insertions(+)

diff --git a/include/util.h b/include/util.h
index 5c3a0a0..6dca655 100644
--- a/include/util.h
+++ b/include/util.h
@@ -206,6 +206,36 @@ static inline void uatomic_set_false(uatomic_bool *val)
 	(typeof(*(p)))ret;				\
 })
 
+/*
+ * refcnt_t: reference counter which can be manipulated by multiple threads
+ * safely
+ */
+
+typedef struct {
+	int val;
+} refcnt_t;
+
+static inline void refcount_set(refcnt_t *rc, int val)
+{
+	uatomic_set(&rc->val, val);
+}
+
+static inline int refcount_read(refcnt_t *rc)
+{
+	return uatomic_read(&rc->val);
+}
+
+static inline int refcount_inc(refcnt_t *rc)
+{
+	return uatomic_add_return(&rc->val, 1);
+}
+
+static inline int refcount_dec(refcnt_t *rc)
+{
+	assert(1 <= uatomic_read(&rc->val));
+	return uatomic_sub_return(&rc->val, 1);
+}
+
 /* colors */
 #define TEXT_NORMAL         "\033[0m"
 #define TEXT_BOLD           "\033[1m"
-- 
1.7.10.4




More information about the sheepdog mailing list