RAUL  0.8.0
AtomicInt.hpp
1 /* This file is part of Raul.
2  * Copyright (C) 2007-2009 David Robillard <http://drobilla.net>
3  *
4  * Raul is free software; you can redistribute it and/or modify it under the
5  * terms of the GNU General Public License as published by the Free Software
6  * Foundation; either version 2 of the License, or (at your option) any later
7  * version.
8  *
9  * Raul is distributed in the hope that it will be useful, but WITHOUT ANY
10  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11  * FOR A PARTICULAR PURPOSE. See the GNU General Public License for details.
12  *
13  * You should have received a copy of the GNU General Public License along
14  * with this program; if not, write to the Free Software Foundation, Inc.,
15  * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
16  */
17 
18 #ifndef RAUL_ATOMIC_INT_HPP
19 #define RAUL_ATOMIC_INT_HPP
20 
21 #include <glib.h>
22 
23 namespace Raul {
24 
25 
29 class AtomicInt {
30 public:
31  inline AtomicInt(int val)
32  { g_atomic_int_set(static_cast<volatile gint*>(&_val), val); }
33 
34  inline AtomicInt(const AtomicInt& copy)
35  { g_atomic_int_set(static_cast<volatile gint*>(&_val), copy.get()); }
36 
37  inline int get() const
38  { return g_atomic_int_get(static_cast<volatile gint*>(&_val)); }
39 
40  inline void operator=(int val)
41  { g_atomic_int_set(static_cast<volatile gint*>(&_val), val); }
42 
43  inline void operator+=(int val)
44  { g_atomic_int_add(static_cast<volatile gint*>(&_val), val); }
45 
46  inline void operator-=(int val)
47  { g_atomic_int_add(static_cast<volatile gint*>(&_val), -val); }
48 
49  inline bool operator==(int val) const
50  { return get() == val; }
51 
52  inline int operator+(int val) const
53  { return get() + val; }
54 
55  inline AtomicInt& operator++() // prefix
56  { g_atomic_int_inc(static_cast<volatile gint*>(&_val)); return *this; }
57 
58  inline AtomicInt& operator--() // prefix
59  { g_atomic_int_add(static_cast<volatile gint*>(&_val), -1); return *this; }
60 
64  inline bool compare_and_exchange(int old, int val)
65  { return g_atomic_int_compare_and_exchange(static_cast<volatile gint*>(&_val), old, val); }
66 
70  inline int exchange_and_add(int val)
71  { return g_atomic_int_exchange_and_add(static_cast<volatile gint*>(&_val), val); }
72 
76  inline bool decrement_and_test()
77  { return g_atomic_int_dec_and_test(static_cast<volatile gint*>(&_val)); }
78 
79 private:
80  volatile mutable int _val;
81 };
82 
83 
84 } // namespace Raul
85 
86 #endif // RAUL_ATOMIC_INT_HPP