SpinLock.h 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /*
  2. * Copyright 2014-present Facebook, Inc.
  3. *
  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
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  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.
  15. */
  16. /*
  17. * N.B. You most likely do _not_ want to use SpinLock or any other
  18. * kind of spinlock. Use std::mutex instead.
  19. *
  20. * In short, spinlocks in preemptive multi-tasking operating systems
  21. * have serious problems and fast mutexes like std::mutex are almost
  22. * certainly the better choice, because letting the OS scheduler put a
  23. * thread to sleep is better for system responsiveness and throughput
  24. * than wasting a timeslice repeatedly querying a lock held by a
  25. * thread that's blocked, and you can't prevent userspace
  26. * programs blocking.
  27. *
  28. * Spinlocks in an operating system kernel make much more sense than
  29. * they do in userspace.
  30. */
  31. #pragma once
  32. #include <type_traits>
  33. #include <boost/noncopyable.hpp>
  34. #include <folly/Portability.h>
  35. #include <folly/synchronization/SmallLocks.h>
  36. namespace folly {
  37. class SpinLock {
  38. public:
  39. FOLLY_ALWAYS_INLINE SpinLock() {
  40. lock_.init();
  41. }
  42. FOLLY_ALWAYS_INLINE void lock() const {
  43. lock_.lock();
  44. }
  45. FOLLY_ALWAYS_INLINE void unlock() const {
  46. lock_.unlock();
  47. }
  48. FOLLY_ALWAYS_INLINE bool try_lock() const {
  49. return lock_.try_lock();
  50. }
  51. private:
  52. mutable folly::MicroSpinLock lock_;
  53. };
  54. template <typename LOCK>
  55. class SpinLockGuardImpl : private boost::noncopyable {
  56. public:
  57. FOLLY_ALWAYS_INLINE explicit SpinLockGuardImpl(LOCK& lock) : lock_(lock) {
  58. lock_.lock();
  59. }
  60. FOLLY_ALWAYS_INLINE ~SpinLockGuardImpl() {
  61. lock_.unlock();
  62. }
  63. private:
  64. LOCK& lock_;
  65. };
  66. typedef SpinLockGuardImpl<SpinLock> SpinLockGuard;
  67. } // namespace folly