OLD | NEW |
1 // Copyright (c) 2015, the Dartino project authors. Please see the AUTHORS file | 1 // Copyright (c) 2015, the Dartino project authors. Please see the AUTHORS file |
2 // for details. All rights reserved. Use of this source code is governed by a | 2 // for details. All rights reserved. Use of this source code is governed by a |
3 // BSD-style license that can be found in the LICENSE.md file. | 3 // BSD-style license that can be found in the LICENSE.md file. |
4 | 4 |
5 #ifndef SRC_VM_SPINLOCK_H_ | 5 #ifndef SRC_VM_SPINLOCK_H_ |
6 #define SRC_VM_SPINLOCK_H_ | 6 #define SRC_VM_SPINLOCK_H_ |
7 | 7 |
8 #include "src/shared/atomic.h" | 8 #include "src/shared/atomic.h" |
9 | 9 |
10 namespace fletch { | 10 namespace dartino { |
11 | 11 |
12 // Please limit the use of spinlocks (e.g. reduce critical region to absolute | 12 // Please limit the use of spinlocks (e.g. reduce critical region to absolute |
13 // minimum, only if a normal mutex is a bottleneck). | 13 // minimum, only if a normal mutex is a bottleneck). |
14 class Spinlock { | 14 class Spinlock { |
15 public: | 15 public: |
16 Spinlock() : is_locked_(false) {} | 16 Spinlock() : is_locked_(false) {} |
17 | 17 |
18 bool IsLocked() const { return is_locked_; } | 18 bool IsLocked() const { return is_locked_; } |
19 | 19 |
20 void Lock() { | 20 void Lock() { |
21 while (is_locked_.exchange(true, kAcquire)) { | 21 while (is_locked_.exchange(true, kAcquire)) { |
22 } | 22 } |
23 } | 23 } |
24 | 24 |
25 void Unlock() { is_locked_.store(false, kRelease); } | 25 void Unlock() { is_locked_.store(false, kRelease); } |
26 | 26 |
27 private: | 27 private: |
28 Atomic<bool> is_locked_; | 28 Atomic<bool> is_locked_; |
29 }; | 29 }; |
30 | 30 |
31 class ScopedSpinlock { | 31 class ScopedSpinlock { |
32 public: | 32 public: |
33 explicit ScopedSpinlock(Spinlock* lock) : lock_(lock) { lock_->Lock(); } | 33 explicit ScopedSpinlock(Spinlock* lock) : lock_(lock) { lock_->Lock(); } |
34 ~ScopedSpinlock() { lock_->Unlock(); } | 34 ~ScopedSpinlock() { lock_->Unlock(); } |
35 | 35 |
36 private: | 36 private: |
37 Spinlock* lock_; | 37 Spinlock* lock_; |
38 }; | 38 }; |
39 | 39 |
40 } // namespace fletch | 40 } // namespace dartino |
41 | 41 |
42 #endif // SRC_VM_SPINLOCK_H_ | 42 #endif // SRC_VM_SPINLOCK_H_ |
OLD | NEW |