1 /******************************************************************************
3 * Copyright (C) 2012-2016 Icinga Development Team (https://www.icinga.org/) *
5 * This program is free software; you can redistribute it and/or *
6 * modify it under the terms of the GNU General Public License *
7 * as published by the Free Software Foundation; either version 2 *
8 * of the License, or (at your option) any later version. *
10 * This program 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 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 Foundation *
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. *
18 ******************************************************************************/
23 #include "base/object.hpp"
25 #define I2MUTEX_UNLOCKED 0
26 #define I2MUTEX_LOCKED 1
32 * A scoped lock for Objects.
34 struct I2_BASE_API ObjectLock {
36 inline ObjectLock(void)
37 : m_Object(NULL), m_Locked(false)
40 inline ~ObjectLock(void)
45 inline ObjectLock(const Object::Ptr& object)
46 : m_Object(object.get()), m_Locked(false)
52 inline ObjectLock(const Object *object)
53 : m_Object(object), m_Locked(false)
59 inline static void LockMutex(const Object *object)
65 while (InterlockedCompareExchange64((LONGLONG *)&object->m_Mutex, I2MUTEX_LOCKED, I2MUTEX_UNLOCKED) != I2MUTEX_UNLOCKED) {
67 while (InterlockedCompareExchange(&object->m_Mutex, I2MUTEX_LOCKED, I2MUTEX_UNLOCKED) != I2MUTEX_UNLOCKED) {
70 while (!__sync_bool_compare_and_swap(&object->m_Mutex, I2MUTEX_UNLOCKED, I2MUTEX_LOCKED)) {
72 if (object->m_Mutex > I2MUTEX_LOCKED) {
73 boost::recursive_mutex *mtx = reinterpret_cast<boost::recursive_mutex *>(object->m_Mutex);
83 boost::recursive_mutex *mtx = new boost::recursive_mutex();
87 InterlockedCompareExchange64((LONGLONG *)&object->m_Mutex, reinterpret_cast<LONGLONG>(mtx), I2MUTEX_LOCKED);
89 InterlockedCompareExchange(&object->m_Mutex, reinterpret_cast<LONG>(mtx), I2MUTEX_LOCKED);
92 __sync_bool_compare_and_swap(&object->m_Mutex, I2MUTEX_LOCKED, reinterpret_cast<uintptr_t>(mtx));
96 inline void Lock(void)
98 ASSERT(!m_Locked && m_Object != NULL);
106 InterlockedExchange(&m_Object->m_LockOwner, GetCurrentThreadId());
108 __sync_lock_test_and_set(&m_Object->m_LockOwner, pthread_self());
110 #endif /* I2_DEBUG */
113 inline static void Spin(unsigned int it)
122 #endif /* SPIN_PAUSE */
132 inline void Unlock(void)
137 InterlockedExchange(&m_Object->m_LockOwner, 0);
139 __sync_lock_release(&m_Object->m_LockOwner);
142 #endif /* I2_DEBUG */
145 reinterpret_cast<boost::recursive_mutex *>(m_Object->m_Mutex)->unlock();
151 const Object *m_Object;
157 #endif /* OBJECTLOCK_H */