3 * Copyright (C) 2005-2009,2011 Mathias Froehlich
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License as
7 * published by the Free Software Foundation; either version 2 of the
8 * License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 # include <simgear_config.h>
25 #include "SGAtomic.hxx"
27 #if defined(SGATOMIC_USE_LIBRARY_FUNCTIONS)
31 #elif defined(GCC_ATOMIC_BUILTINS_FOUND)
32 #elif defined(__GNUC__) && defined(__i386__)
33 #elif defined(SGATOMIC_USE_MUTEX)
34 # include <simgear/threads/SGGuard.hxx>
40 SGAtomic::operator++()
43 return InterlockedIncrement(reinterpret_cast<long volatile*>(&mValue));
44 #elif defined(GCC_ATOMIC_BUILTINS_FOUND)
45 return __sync_add_and_fetch(&mValue, 1);
46 #elif defined(__GNUC__) && defined(__i386__)
47 register volatile unsigned* mem = reinterpret_cast<volatile unsigned*>(&mValue);
48 register unsigned result;
49 __asm__ __volatile__("lock; xadd{l} {%0,%1|%1,%0}"
50 : "=r" (result), "=m" (*mem)
55 SGGuard<SGMutex> lock(mMutex);
61 SGAtomic::operator--()
64 return InterlockedDecrement(reinterpret_cast<long volatile*>(&mValue));
65 #elif defined(GCC_ATOMIC_BUILTINS_FOUND)
66 return __sync_sub_and_fetch(&mValue, 1);
67 #elif defined(__GNUC__) && defined(__i386__)
68 register volatile unsigned* mem = reinterpret_cast<volatile unsigned*>(&mValue);
69 register unsigned result;
70 __asm__ __volatile__("lock; xadd{l} {%0,%1|%1,%0}"
71 : "=r" (result), "=m" (*mem)
72 : "0" (-1), "m" (*mem)
76 SGGuard<SGMutex> lock(mMutex);
81 SGAtomic::operator unsigned() const
84 return static_cast<unsigned const volatile &>(mValue);
85 #elif defined(GCC_ATOMIC_BUILTINS_FOUND)
88 #elif defined(__GNUC__) && defined(__i386__)
89 __asm__ __volatile__("": : : "memory");
92 SGGuard<SGMutex> lock(mMutex);
98 SGAtomic::compareAndExchange(unsigned oldValue, unsigned newValue)
101 long volatile* lvPtr = reinterpret_cast<long volatile*>(&mValue);
102 return oldValue == InterlockedCompareExchange(lvPtr, newValue, oldValue);
103 #elif defined(GCC_ATOMIC_BUILTINS_FOUND)
104 return __sync_bool_compare_and_swap(&mValue, oldValue, newValue);
105 #elif defined(__GNUC__) && defined(__i386__)
106 register volatile unsigned* mem = reinterpret_cast<volatile unsigned*>(&mValue);
108 __asm__ __volatile__("lock; cmpxchg{l} {%1,%2|%1,%2}"
110 : "q"(newValue), "m"(*mem), "0"(oldValue)
112 return before == oldValue;
114 SGGuard<SGMutex> lock(mMutex);
115 if (mValue != oldValue)