summaryrefslogtreecommitdiff
path: root/src/common/ref.h
blob: 13a70374dd4008fe974b1dbe34e5517a75fee6d9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/*  Copyright (C) 2011 CZ.NIC, z.s.p.o. <knot-dns@labs.nic.cz>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
/*!
 * \file ref.h
 *
 * \author Marek Vavrusa <marek.vavrusa@nic.cz>
 *
 * \brief Atomic reference counting structures.
 *
 * Reference counting allows implicit sharing of objects
 * between threads with custom destructor functions.
 *
 * \addtogroup common_lib
 * @{
 */

#ifndef _KNOTD_REF_H_
#define _KNOTD_REF_H_

#include <stddef.h>

struct ref_t;

/*! \brief Prototype for object destructor callback. */
typedef void (*ref_destructor_t)(struct ref_t * p);

/*!
 * \brief Structure for reference counting.
 *
 * Size equals to two sizes of pointer size.
 * Structure may be embedded to the structures which
 * we want to use for reference counting.
 *
 * \code
 * struct mystruct {
 *    ref_t ref;
 *    int mydata;
 *    char *mystr;
 * }
 * \endcode
 */
typedef struct ref_t {
	size_t count;          /*! \brief Reference counter. */
	ref_destructor_t dtor; /*! \brief Object destructor function. */
} ref_t;

/*!
 * \brief Initialize reference counter.
 *
 * Set reference counter to 0 and initialize destructor callback.
 *
 * \param p Reference-counted object.
 * \param dtor Destructor function.
 */
void ref_init(ref_t *p, ref_destructor_t dtor);

/*!
 * \brief Mark object as used by the caller.
 *
 * Reference counter will be incremented.
 *
 * \param p Reference-counted object.
 */
void ref_retain(ref_t *p);

/*!
 * \brief Marks object as unused by the caller.
 *
 * Reference counter will be decremented.
 *
 * \param p Reference-counted object.
 */
void ref_release(ref_t *p);

#endif /* _KNOTD_REF_H_ */

/*! @} */