• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef THIRD_PARTY_BASE_ALLOCATOR_PARTITION_ALLOCATOR_SPIN_LOCK_H_
6 #define THIRD_PARTY_BASE_ALLOCATOR_PARTITION_ALLOCATOR_SPIN_LOCK_H_
7 
8 #include <atomic>
9 #include <memory>
10 #include <mutex>
11 
12 #include "third_party/base/base_export.h"
13 #include "third_party/base/compiler_specific.h"
14 
15 // Spinlock is a simple spinlock class based on the standard CPU primitive of
16 // atomic increment and decrement of an int at a given memory address. These are
17 // intended only for very short duration locks and assume a system with multiple
18 // cores. For any potentially longer wait you should use a real lock, such as
19 // |base::Lock|.
20 namespace pdfium {
21 namespace base {
22 namespace subtle {
23 
24 class BASE_EXPORT SpinLock {
25  public:
26   constexpr SpinLock() = default;
27   ~SpinLock() = default;
28   using Guard = std::lock_guard<SpinLock>;
29 
lock()30   ALWAYS_INLINE void lock() {
31     static_assert(sizeof(lock_) == sizeof(int),
32                   "int and lock_ are different sizes");
33     if (LIKELY(!lock_.exchange(true, std::memory_order_acquire)))
34       return;
35     LockSlow();
36   }
37 
unlock()38   ALWAYS_INLINE void unlock() { lock_.store(false, std::memory_order_release); }
39 
40  private:
41   // This is called if the initial attempt to acquire the lock fails. It's
42   // slower, but has a much better scheduling and power consumption behavior.
43   void LockSlow();
44 
45   std::atomic_int lock_{0};
46 };
47 
48 }  // namespace subtle
49 }  // namespace base
50 }  // namespace pdfium
51 
52 #endif  // THIRD_PARTY_BASE_ALLOCATOR_PARTITION_ALLOCATOR_SPIN_LOCK_H_
53