Fix: tests: invoke destroy APIs for queues/stacks
[urcu.git] / urcu / ref.h
... / ...
CommitLineData
1#ifndef _URCU_REF_H
2#define _URCU_REF_H
3
4/*
5 * Userspace RCU - Reference counting
6 *
7 * Copyright (C) 2009 Novell Inc.
8 * Copyright (C) 2010 Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
9 *
10 * Author: Jan Blunck <jblunck@suse.de>
11 *
12 * This program is free software; you can redistribute it and/or modify it
13 * under the terms of the GNU Lesser General Public License version 2.1 as
14 * published by the Free Software Foundation.
15 */
16
17#include <assert.h>
18#include <stdbool.h>
19#include <limits.h>
20#include <stdlib.h>
21#include <urcu/uatomic.h>
22
23struct urcu_ref {
24 long refcount; /* ATOMIC */
25};
26
27static inline void urcu_ref_set(struct urcu_ref *ref, long val)
28{
29 uatomic_set(&ref->refcount, val);
30}
31
32static inline void urcu_ref_init(struct urcu_ref *ref)
33{
34 urcu_ref_set(ref, 1);
35}
36
37static inline bool __attribute__((warn_unused_result))
38 urcu_ref_get_safe(struct urcu_ref *ref)
39{
40 long old, _new, res;
41
42 old = uatomic_read(&ref->refcount);
43 for (;;) {
44 if (old == LONG_MAX) {
45 return false; /* Failure. */
46 }
47 _new = old + 1;
48 res = uatomic_cmpxchg(&ref->refcount, old, _new);
49 if (res == old) {
50 return true; /* Success. */
51 }
52 old = res;
53 }
54}
55
56static inline void urcu_ref_get(struct urcu_ref *ref)
57{
58 if (!urcu_ref_get_safe(ref))
59 abort();
60}
61
62static inline void urcu_ref_put(struct urcu_ref *ref,
63 void (*release)(struct urcu_ref *))
64{
65 long res = uatomic_sub_return(&ref->refcount, 1);
66 assert (res >= 0);
67 if (res == 0)
68 release(ref);
69}
70
71/*
72 * urcu_ref_get_unless_zero
73 *
74 * Allows getting a reference atomically if the reference count is not
75 * zero. Returns true if the reference is taken, false otherwise. This
76 * needs to be used in conjunction with another synchronization
77 * technique (e.g. RCU or mutex) to ensure existence of the reference
78 * count. False is also returned in case incrementing the refcount would
79 * result in an overflow.
80 */
81static inline bool urcu_ref_get_unless_zero(struct urcu_ref *ref)
82{
83 long old, _new, res;
84
85 old = uatomic_read(&ref->refcount);
86 for (;;) {
87 if (old == 0 || old == LONG_MAX)
88 return false; /* Failure. */
89 _new = old + 1;
90 res = uatomic_cmpxchg(&ref->refcount, old, _new);
91 if (res == old) {
92 return true; /* Success. */
93 }
94 old = res;
95 }
96}
97
98#endif /* _URCU_REF_H */
This page took 0.022109 seconds and 4 git commands to generate.