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>
21 // This is a wrapper SpinLock implementation that works around the
22 // x64 limitation of the base folly MicroSpinLock. If that is available, this
23 // simply thinly wraps it. Otherwise, it uses the simplest analog available on
24 // iOS (or 32-bit Mac) or, failing that, POSIX (on Android et. al.)
27 #include <folly/SmallLocks.h>
29 namespace folly { namespace io {
31 class PortableSpinLock {
33 FOLLY_ALWAYS_INLINE PortableSpinLock() {
36 FOLLY_ALWAYS_INLINE void lock() const {
39 FOLLY_ALWAYS_INLINE void unlock() const {
42 FOLLY_ALWAYS_INLINE bool trylock() const {
43 return lock_.try_lock();
46 mutable folly::MicroSpinLock lock_;
52 #include <libkern/OSAtomic.h>
54 namespace folly { namespace io {
56 class PortableSpinLock {
58 FOLLY_ALWAYS_INLINE PortableSpinLock() : lock_(0) {}
59 FOLLY_ALWAYS_INLINE void lock() const {
60 OSSpinLockLock(&lock_);
62 FOLLY_ALWAYS_INLINE void unlock() const {
63 OSSpinLockUnlock(&lock_);
65 FOLLY_ALWAYS_INLINE bool trylock() const {
66 return OSSpinLockTry(&lock_);
69 mutable OSSpinLock lock_;
77 namespace folly { namespace io {
79 class PortableSpinLock {
81 FOLLY_ALWAYS_INLINE PortableSpinLock() {
82 pthread_mutex_init(&lock_, nullptr);
85 int rc = pthread_mutex_lock(&lock_);
88 FOLLY_ALWAYS_INLINE void unlock() const {
89 int rc = pthread_mutex_unlock(&lock_);
92 FOLLY_ALWAYS_INLINE bool trylock() const {
93 int rc = pthread_mutex_trylock(&lock_);
98 mutable pthread_mutex_t lock_;
105 namespace folly { namespace io {
107 class PortableSpinLockGuard : private boost::noncopyable {
109 FOLLY_ALWAYS_INLINE explicit PortableSpinLockGuard(PortableSpinLock& lock) :
113 FOLLY_ALWAYS_INLINE ~PortableSpinLockGuard() {
117 PortableSpinLock& lock_;