[vlc-devel] [PATCH v2 01/10] core: add atomic refcounter helper
Hugo Beauzée-Luyssen
hugo at beauzee.fr
Mon Jul 2 17:04:05 CEST 2018
On Mon, Jul 2, 2018, at 7:49 AM, Romain Vimont wrote:
> Implement an atomic refcounter with a weak but correct (1) memory order,
> and expose a simple API.
>
> (1) See for example "Using weakly ordered C++ atomics correctly" by Hans
> Boehm at CppCon 2016 (the refcounting part also applies to C11):
> <https://www.youtube.com/watch?v=M15UKpNlpeM&t=45m15s>
> ---
> include/vlc_atomic.h | 25 +++++++++++++++++++++++++
> 1 file changed, 25 insertions(+)
>
> diff --git a/include/vlc_atomic.h b/include/vlc_atomic.h
> index 868918fe8e6..2cb5e23f489 100644
> --- a/include/vlc_atomic.h
> +++ b/include/vlc_atomic.h
> @@ -30,6 +30,7 @@
> * Atomic operations do not require locking, but they are not very powerful.
> */
>
> +# include <assert.h>
> # include <stdatomic.h>
>
> typedef atomic_uint_least32_t vlc_atomic_float;
> @@ -57,4 +58,28 @@ static inline void
> vlc_atomic_store_float(vlc_atomic_float *atom, float f)
> atomic_store(atom, u.i);
> }
>
> +typedef atomic_uint vlc_atomic_rc_t;
> +
> +/** Init the RC to 1 */
> +static inline void vlc_atomic_rc_init(vlc_atomic_rc_t *var)
> +{
> + atomic_init(var, 1);
> +}
> +
> +/** Increment the RC */
> +static inline void vlc_atomic_rc_inc(vlc_atomic_rc_t *var)
> +{
> + unsigned prev = atomic_fetch_add_explicit(var, 1, memory_order_relaxed);
> + assert(prev);
> + VLC_UNUSED(prev);
> +}
> +
> +/** Decrement the RC and return true if it reaches 0 */
> +static inline bool vlc_atomic_rc_dec(vlc_atomic_rc_t *var)
> +{
> + unsigned prev = atomic_fetch_sub_explicit(var, 1, memory_order_acq_rel);
> + assert(prev);
> + return prev == 1;
> +}
> +
> #endif
> --
> 2.18.0
>
The entire set looks good to me
--
Hugo Beauzée-Luyssen
hugo at beauzee.fr
More information about the vlc-devel
mailing list