2 * Copyright 2014 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
19 #include <boost/noncopyable.hpp>
20 #include <folly/Portability.h>
22 // This is a wrapper SpinLock implementation that works around the
23 // x64 limitation of the base folly MicroSpinLock. If that is available, this
24 // simply thinly wraps it. Otherwise, it uses the simplest analog available on
25 // iOS (or 32-bit Mac) or, failing that, POSIX (on Android et. al.)
28 #include <folly/SmallLocks.h>
34 FOLLY_ALWAYS_INLINE SpinLock() {
37 FOLLY_ALWAYS_INLINE void lock() const {
40 FOLLY_ALWAYS_INLINE void unlock() const {
43 FOLLY_ALWAYS_INLINE bool trylock() const {
44 return lock_.try_lock();
47 mutable folly::MicroSpinLock lock_;
53 #include <libkern/OSAtomic.h>
59 FOLLY_ALWAYS_INLINE SpinLock() : lock_(0) {}
60 FOLLY_ALWAYS_INLINE void lock() const {
61 OSSpinLockLock(&lock_);
63 FOLLY_ALWAYS_INLINE void unlock() const {
64 OSSpinLockUnlock(&lock_);
66 FOLLY_ALWAYS_INLINE bool trylock() const {
67 return OSSpinLockTry(&lock_);
70 mutable OSSpinLock lock_;
77 #include <glog/logging.h>
83 FOLLY_ALWAYS_INLINE SpinLock() {
84 pthread_mutex_init(&lock_, nullptr);
87 int rc = pthread_mutex_lock(&lock_);
90 FOLLY_ALWAYS_INLINE void unlock() const {
91 int rc = pthread_mutex_unlock(&lock_);
94 FOLLY_ALWAYS_INLINE bool trylock() const {
95 int rc = pthread_mutex_trylock(&lock_);
100 mutable pthread_mutex_t lock_;
109 class SpinLockGuard : private boost::noncopyable {
111 FOLLY_ALWAYS_INLINE explicit SpinLockGuard(SpinLock& lock) :
115 FOLLY_ALWAYS_INLINE ~SpinLockGuard() {