blob: 0c58f917a10c991edf70c1e4473c95cb2b92cb4e [file] [log] [blame]
Alexandre Lisionddd731e2014-01-31 11:50:08 -05001// Copyright (C) 2006-2010 David Sugar, Tycho Softworks.
2//
3// This file is part of GNU uCommon C++.
4//
5// GNU uCommon C++ is free software: you can redistribute it and/or modify
6// it under the terms of the GNU Lesser General Public License as published
7// by the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// GNU uCommon C++ is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU Lesser General Public License for more details.
14//
15// You should have received a copy of the GNU Lesser General Public License
16// along with GNU uCommon C++. If not, see <http://www.gnu.org/licenses/>.
17
18/**
19 * Atomic pointers and locks. These are meant to use atomic CPU operations
20 * and hence offer maximum performance.
21 * @file ucommon/atomic.h
22 * @author David Sugar <dyfet@gnutelephony.org>
23 */
24
25#ifndef _UCOMMON_ATOMIC_H_
26#define _UCOMMON_ATOMIC_H_
27
28#ifndef _UCOMMON_CONFIG_H_
29#include <ucommon/platform.h>
30#endif
31
32NAMESPACE_UCOMMON
33
34/**
35 * Generic atomic class for referencing atomic objects and static functions.
36 * We have an atomic counter and spinlock, and in the future we may add
37 * other atomic classes and atomic manipulations needed to create lockfree
38 * data structures. The atomic classes use mutexes if no suitable atomic
39 * code is available.
40 * @author David Sugar <dyfet@gnutelephony.org>
41 */
42class __EXPORT atomic
43{
44public:
45 /**
46 * Set to true if atomics have to be simulated with mutexes.
47 */
48 static const bool simulated;
49
50 /**
51 * Atomic counter class. Can be used to manipulate value of an
52 * atomic counter without requiring explicit thread locking.
53 * @author David Sugar <dyfet@gnutelephony.org>
54 */
55 class __EXPORT counter
56 {
57 private:
58 volatile long value;
59
60 public:
61 counter(long initial = 0);
62
63 long operator++();
64 long operator--();
65 long operator+=(long offset);
66 long operator-=(long offset);
67
68 inline operator long()
69 {return (long)(value);};
70
71 inline long operator*()
72 {return value;};
73 };
74
75 /**
76 * Atomic spinlock class. Used as high-performance sync lock between
77 * threads.
78 * @author David Sugar <dyfet@gnutelephony.org>
79 */
80 class __EXPORT spinlock
81 {
82 private:
83 volatile long value;
84
85 public:
86 /**
87 * Construct and initialize spinlock.
88 */
89 spinlock();
90
91 /**
92 * Acquire the lock. If the lock is not acquired, one "spins"
93 * by doing something else. One suggestion is using thread::yield.
94 * @return true if acquired.
95 */
96 bool acquire(void);
97
98 /**
99 * Release an acquired spinlock.
100 */
101 void release(void);
102 };
103};
104
105END_NAMESPACE
106
107#endif