Let Futex import base-class ctors
[folly.git] / folly / SpinLock.h
index 0acbca899952813d816aa50bc7900a1145c402dd..a735fcd17d60382833ab7d4103303b63b282ab42 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2016 Facebook, Inc.
+ * Copyright 2017 Facebook, Inc.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * limitations under the License.
  */
 
+/*
+ * N.B. You most likely do _not_ want to use SpinLock or any other
+ * kind of spinlock.  Use std::mutex instead.
+ *
+ * In short, spinlocks in preemptive multi-tasking operating systems
+ * have serious problems and fast mutexes like std::mutex are almost
+ * certainly the better choice, because letting the OS scheduler put a
+ * thread to sleep is better for system responsiveness and throughput
+ * than wasting a timeslice repeatedly querying a lock held by a
+ * thread that's blocked, and you can't prevent userspace
+ * programs blocking.
+ *
+ * Spinlocks in an operating system kernel make much more sense than
+ * they do in userspace.
+ */
+
 #pragma once
 
-#include <folly/detail/SpinLockImpl.h>
+#include <type_traits>
+
+#include <boost/noncopyable.hpp>
+
+#include <folly/Portability.h>
+#include <folly/SmallLocks.h>
 
 namespace folly {
 
-#if __x86_64__
-typedef SpinLockMslImpl SpinLock;
-#elif __APPLE__
-typedef SpinLockAppleImpl SpinLock;
-#elif FOLLY_HAVE_PTHREAD_SPINLOCK_T
-typedef SpinLockPthreadImpl SpinLock;
-#else
-typedef SpinLockPthreadMutexImpl SpinLock;
-#endif
+class SpinLock {
+ public:
+  FOLLY_ALWAYS_INLINE SpinLock() {
+    lock_.init();
+  }
+  FOLLY_ALWAYS_INLINE void lock() const {
+    lock_.lock();
+  }
+  FOLLY_ALWAYS_INLINE void unlock() const {
+    lock_.unlock();
+  }
+  FOLLY_ALWAYS_INLINE bool try_lock() const {
+    return lock_.try_lock();
+  }
+
+ private:
+  mutable folly::MicroSpinLock lock_;
+};
 
 template <typename LOCK>
 class SpinLockGuardImpl : private boost::noncopyable {
@@ -46,4 +76,4 @@ class SpinLockGuardImpl : private boost::noncopyable {
 
 typedef SpinLockGuardImpl<SpinLock> SpinLockGuard;
 
-}
+} // namespace folly