Files
mongo/util/concurrency/spin_lock.cpp

102 lines
2.5 KiB
C++
Raw Normal View History

// spin_lock.cpp
/**
* Copyright (C) 2010 10gen Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
2010-08-26 21:09:51 -04:00
#include "pch.h"
#include <time.h>
#include "spin_lock.h"
namespace mongo {
2011-01-04 00:40:41 -05:00
SpinLock::~SpinLock() {
2010-08-26 23:51:03 -04:00
#if defined(_WIN32)
DeleteCriticalSection(&_cs);
2011-05-10 16:48:30 -04:00
#elif defined(__USE_XOPEN2K)
pthread_spin_destroy(&_lock);
2010-08-26 23:51:03 -04:00
#endif
}
2010-08-26 22:10:13 -04:00
SpinLock::SpinLock()
2011-05-10 16:48:30 -04:00
#if defined(_WIN32)
2010-08-26 22:10:13 -04:00
{ InitializeCriticalSectionAndSpinCount(&_cs, 4000); }
2011-05-10 16:48:30 -04:00
#elif defined(__USE_XOPEN2K)
{ pthread_spin_init( &_lock , 0 ); }
#elif defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4)
: _locked( false ) { }
2010-08-26 17:51:18 -04:00
#else
2011-05-10 16:48:30 -04:00
: _mutex( "SpinLock" ) { }
#endif
2011-01-04 00:40:41 -05:00
void SpinLock::lock() {
2011-05-10 16:48:30 -04:00
#if defined(_WIN32)
EnterCriticalSection(&_cs);
#elif defined(__USE_XOPEN2K)
pthread_spin_lock( &_lock );
2011-05-10 16:48:30 -04:00
#elif defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4)
// fast path
if (!_locked && !__sync_lock_test_and_set(&_locked, true)) {
return;
}
// wait for lock
int wait = 1000;
while ((wait-- > 0) && (_locked)) {
asm volatile ( "pause" ) ;
}
// if failed to grab lock, sleep
struct timespec t;
t.tv_sec = 0;
t.tv_nsec = 5000000;
while (__sync_lock_test_and_set(&_locked, true)) {
nanosleep(&t, NULL);
}
#else
// WARNING Missing spin lock in this platform. This can potentially
// be slow.
2010-08-26 17:44:55 -04:00
_mutex.lock();
#endif
}
2011-01-04 00:40:41 -05:00
void SpinLock::unlock() {
2011-05-11 11:45:47 -04:00
#if defined(_WIN32)
2010-08-26 22:10:13 -04:00
LeaveCriticalSection(&_cs);
2011-05-10 16:48:30 -04:00
#elif defined(__USE_XOPEN2K)
pthread_spin_unlock(&_lock);
#elif defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4)
__sync_lock_release(&_locked);
#else
_mutex.unlock();
2011-05-10 16:48:30 -04:00
#endif
}
2011-05-10 16:48:30 -04:00
bool SpinLock::isfast() {
#if defined(_WIN32)
return true;
#elif defined(__USE_XOPEN2K)
return true;
#elif defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4)
return true;
#else
return false;
#endif
}
2011-05-10 16:48:30 -04:00
} // namespace mongo