-
Notifications
You must be signed in to change notification settings - Fork 1
/
wait_ops.hpp
114 lines (73 loc) · 2.73 KB
/
wait_ops.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
/**
* @file wait_ops.hpp
* @author F. Abrignani (federignoli@hotmail.it)
* @author S. Martorana
* @brief This file contains the implementation of the wait operations used by the mutexes.
* @version 0.1
* @date 2023-10-06
*
* @copyright Copyright (c) 2023 Federico Abrignani (federignoli@hotmail.it).
* Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt).
*
*/
#ifndef BOOST_FAIRNESS_WAIT_OPS_HPP
#define BOOST_FAIRNESS_WAIT_OPS_HPP
#include <boost/fairness/config.hpp>
#include <boost/fairness/detail/pause_ops.hpp>
#include <atomic>
#include <thread>
#include <functional>
namespace boost::fairness::detail{
static const std::function<void()> relaxOrYield[] = {pause ,std::this_thread::yield};
template<typename T ,typename K>
inline void spin_wait(T& mem, K const expected) noexcept {
for(int i = 0; i < BOOST_FAIRNESS_SPINWAIT_SPINS; ++i){
if (mem.load(std::memory_order_relaxed) != expected)
return;
relaxOrYield[i >= BOOST_FAIRNESS_SPINWAIT_SPINS_RELAXED]();
}
}
template<typename K>
inline void spin_wait(std::atomic_flag& mem, K const expected) noexcept {
for(int i = 0; i < BOOST_FAIRNESS_SPINWAIT_SPINS; ++i){
if (mem.test(std::memory_order_relaxed) != expected)
return;
relaxOrYield[i >= BOOST_FAIRNESS_SPINWAIT_SPINS_RELAXED]();
}
}
inline void spin_wait() noexcept {
for(int i = 0; i < BOOST_FAIRNESS_GETREQUEST_SPINS; ++i){
relaxOrYield[i >= BOOST_FAIRNESS_GETREQUEST_SPINS_RELAXED]();
}
}
#if !defined(BOOST_FAIRNESS_USE_STD_WAIT_NOTIFY)
template<typename T, typename K>
inline void wait(T& mem, K const expected) noexcept {
auto memEqualsExpected = [&mem, expected]{
return mem.load(std::memory_order_relaxed) == expected;
};
do {
for(int i = 0; i < BOOST_FAIRNESS_WAIT_SPINS; ++i){
if (!memEqualsExpected())
return;
relaxOrYield[i >= BOOST_FAIRNESS_WAIT_SPINS_RELAXED]();
}
wait_(mem, expected);
} while (memEqualsExpected());
}
#else // defined(BOOST_FAIRNESS_USE_STD_WAIT_NOTIFY)
template<typename T, typename K>
inline void wait(T& mem, K expected) noexcept {
wait_(mem, expected);
}
#endif // BOOST_FAIRNESS_USE_STD_WAIT_NOTIFY
template<typename T>
inline void notify_one(T& mem) noexcept {
notify_one_(mem);
}
template<typename T>
inline void notify_all(T& mem) noexcept {
notify_all_(mem);
}
}
#endif // BOOST_FAIRNESS_WAIT_OPS_HPP