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__)
34 # include <simgear/threads/SGGuard.hxx>
38 SGAtomic::operator++()
41 return InterlockedIncrement(reinterpret_cast<long volatile*>(&mValue));
42 #elif defined(GCC_ATOMIC_BUILTINS_FOUND)
43 return __sync_add_and_fetch(&mValue, 1);
44 #elif defined(__GNUC__) && defined(__i386__)
45 register volatile unsigned* mem = reinterpret_cast<volatile unsigned*>(&mValue);
46 register unsigned result;
47 __asm__ __volatile__("lock; xadd{l} {%0,%1|%1,%0}"
48 : "=r" (result), "=m" (*mem)
53 SGGuard<SGMutex> lock(mMutex);
59 SGAtomic::operator--()
62 return InterlockedDecrement(reinterpret_cast<long volatile*>(&mValue));
63 #elif defined(GCC_ATOMIC_BUILTINS_FOUND)
64 return __sync_sub_and_fetch(&mValue, 1);
65 #elif defined(__GNUC__) && defined(__i386__)
66 register volatile unsigned* mem = reinterpret_cast<volatile unsigned*>(&mValue);
67 register unsigned result;
68 __asm__ __volatile__("lock; xadd{l} {%0,%1|%1,%0}"
69 : "=r" (result), "=m" (*mem)
70 : "0" (-1), "m" (*mem)
74 SGGuard<SGMutex> lock(mMutex);
79 SGAtomic::operator unsigned() const
82 return static_cast<unsigned const volatile &>(mValue);
83 #elif defined(GCC_ATOMIC_BUILTINS_FOUND)
86 #elif defined(__GNUC__) && defined(__i386__)
87 __asm__ __volatile__("": : : "memory");
90 SGGuard<SGMutex> lock(mMutex);
96 SGAtomic::compareAndExchange(unsigned oldValue, unsigned newValue)
99 long volatile* lvPtr = reinterpret_cast<long volatile*>(&mValue);
100 return oldValue == InterlockedCompareExchange(lvPtr, newValue, oldValue);
101 #elif defined(GCC_ATOMIC_BUILTINS_FOUND)
102 return __sync_bool_compare_and_swap(&mValue, oldValue, newValue);
103 #elif defined(__GNUC__) && defined(__i386__)
104 register volatile unsigned* mem = reinterpret_cast<volatile unsigned*>(&mValue);
106 __asm__ __volatile__("lock; cmpxchg{l} {%1,%2|%1,%2}"
108 : "q"(newValue), "m"(*mem), "0"(oldValue)
110 return before == oldValue;
112 SGGuard<SGMutex> lock(mMutex);
113 if (mValue != oldValue)