-
Notifications
You must be signed in to change notification settings - Fork 34
/
spin_lock.hpp
59 lines (50 loc) · 1.39 KB
/
spin_lock.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/**
* Copyright Quadrivium LLC
* All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*/
#pragma once
#include <atomic>
namespace kagome::common {
/**
* Implements a spin lock synchronization primitive.
*
* Does busy-waiting over an atomic flag, thus the best application would
* be for the cases when the lock is required for a very short amount of time
* (to perform very few and finite computational steps under the lock).
*
* An advantage over std::mutex is locking without a call to system's kernel
* and eliminating expensive context switches.
*
* Can be used with std::lock_guard:
* @code
* spin_lock mutex;
* {
* std::lock_guard lock(mutex);
* // synchronized computations go here
* }
* @endcode
*/
class spin_lock { // the name styling is unified with std
public:
spin_lock() = default;
spin_lock(const spin_lock &) = delete;
spin_lock(spin_lock &&) = delete;
~spin_lock() = default;
spin_lock &operator=(const spin_lock &) = delete;
spin_lock &operator=(spin_lock &&) = delete;
/**
* Acquires the lock.
*
* Blocks thread execution until the other thread releases the lock in a
* busy-waiting manner.
*/
void lock();
/**
* Releases the lock.
*/
void unlock();
private:
std::atomic_flag flag_ = ATOMIC_FLAG_INIT;
};
} // namespace kagome::common