1 /******************************************************************************
3 * Copyright (C) 2012-2018 Icinga Development Team (https://www.icinga.com/) *
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 ******************************************************************************/
20 #include "base/objectlock.hpp"
21 #include <boost/thread/recursive_mutex.hpp>
23 using namespace icinga;
25 #define I2MUTEX_UNLOCKED 0
26 #define I2MUTEX_LOCKED 1
28 ObjectLock::~ObjectLock()
33 ObjectLock::ObjectLock(const Object::Ptr& object)
34 : m_Object(object.get()), m_Locked(false)
40 ObjectLock::ObjectLock(const Object *object)
41 : m_Object(object), m_Locked(false)
47 void ObjectLock::LockMutex(const Object *object)
53 while (likely(InterlockedCompareExchange64((LONGLONG *)&object->m_Mutex, I2MUTEX_LOCKED, I2MUTEX_UNLOCKED) != I2MUTEX_UNLOCKED)) {
55 while (likely(InterlockedCompareExchange(&object->m_Mutex, I2MUTEX_LOCKED, I2MUTEX_UNLOCKED) != I2MUTEX_UNLOCKED)) {
58 while (likely(!__sync_bool_compare_and_swap(&object->m_Mutex, I2MUTEX_UNLOCKED, I2MUTEX_LOCKED))) {
60 if (likely(object->m_Mutex > I2MUTEX_LOCKED)) {
61 auto *mtx = reinterpret_cast<boost::recursive_mutex *>(object->m_Mutex);
71 auto *mtx = new boost::recursive_mutex();
75 InterlockedCompareExchange64((LONGLONG *)&object->m_Mutex, reinterpret_cast<LONGLONG>(mtx), I2MUTEX_LOCKED);
77 InterlockedCompareExchange(&object->m_Mutex, reinterpret_cast<LONG>(mtx), I2MUTEX_LOCKED);
80 __sync_bool_compare_and_swap(&object->m_Mutex, I2MUTEX_LOCKED, reinterpret_cast<uintptr_t>(mtx));
84 void ObjectLock::Lock()
86 ASSERT(!m_Locked && m_Object);
94 InterlockedExchange(&m_Object->m_LockOwner, GetCurrentThreadId());
96 __sync_lock_test_and_set(&m_Object->m_LockOwner, pthread_self());
101 void ObjectLock::Spin(unsigned int it)
110 #endif /* SPIN_PAUSE */
120 void ObjectLock::Unlock()
125 InterlockedExchange(&m_Object->m_LockOwner, 0);
127 __sync_lock_release(&m_Object->m_LockOwner);
130 #endif /* I2_DEBUG */
133 reinterpret_cast<boost::recursive_mutex *>(m_Object->m_Mutex)->unlock();