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

Hitoshi Mitake mitake.hitoshi at gmail.com
Wed Jul 10 04:01:36 CEST 2013


At Tue, 9 Jul 2013 16:59:27 +0800,
Liu Yuan wrote:
> 
> On Tue, Jul 09, 2013 at 04:42:01PM +0900, Hitoshi Mitake wrote:
> > 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 |   36 ++++++++++++++++++++++++++++++++++++
> >  1 file changed, 36 insertions(+)
> > 
> > diff --git a/include/util.h b/include/util.h
> > index 1517680..7e60ccc 100644
> > --- a/include/util.h
> > +++ b/include/util.h
> > @@ -212,6 +212,42 @@ 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 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);
> > +}
> 
> I don't think this refcnt_dec_return is atomic operatoin. You should rely on the
> atomic_sub_return()...anyway, I am not yet convinced to use wrapper instead of
> atomic helpers.

Sorry, the definition of refcnt_dec_return() is wrong, as you pointed.

The benefit of using this specialized type for reference counters is
shown in the last patch of this series. We can enforce correct
reference counting by the compiler level type checking.

Thanks,
Hitoshi



More information about the sheepdog mailing list