Skip to content

Commit eaff7b1

Browse files
Nicoshevfacebook-github-bot
authored andcommitted
Refactor sleeper
Summary: Propose refactoring changes, that were pending from landed diff D70250664 Two main changes are preferring C++ over pre-processor and structuring the code in a way spinCount<kMaxActiveSpin invariant is guaranteed to hold Reviewed By: yfeldblum Differential Revision: D70581321 fbshipit-source-id: 8db35d9e7cb314e6d21026011a4891a3bc7e5c05
1 parent 801634a commit eaff7b1

File tree

1 file changed

+19
-17
lines changed

1 file changed

+19
-17
lines changed

folly/synchronization/detail/Sleeper.h

+19-17
Original file line numberDiff line numberDiff line change
@@ -34,34 +34,36 @@ namespace detail {
3434
*/
3535
class Sleeper {
3636
const std::chrono::nanoseconds delta;
37-
uint32_t spinCount;
38-
39-
#if FOLLY_AARCH64 && !FOLLY_MOBILE
40-
uint32_t spinCountLog = 1;
41-
#endif
4237

4338
static constexpr uint32_t kMaxActiveSpin = 4096;
39+
static constexpr bool useBackOff = kIsArchAArch64 && !kIsMobile;
40+
41+
uint32_t spinCount = 0;
42+
43+
uint32_t spinCountTarget = 1;
4444

4545
public:
4646
static constexpr std::chrono::nanoseconds kMinYieldingSleep =
4747
std::chrono::microseconds(500);
4848

49-
constexpr Sleeper() noexcept : delta(kMinYieldingSleep), spinCount(0) {}
49+
constexpr Sleeper() noexcept : delta(kMinYieldingSleep) {}
5050

51-
explicit Sleeper(std::chrono::nanoseconds d) noexcept
52-
: delta(d), spinCount(0) {}
51+
explicit Sleeper(std::chrono::nanoseconds d) noexcept : delta(d) {}
5352

5453
void wait() noexcept {
55-
if (spinCount < kMaxActiveSpin) {
56-
#if FOLLY_AARCH64 && !FOLLY_MOBILE
57-
do {
54+
bool doSpin = useBackOff
55+
? spinCountTarget <= kMaxActiveSpin
56+
: spinCount < kMaxActiveSpin;
57+
if (doSpin) {
58+
if constexpr (useBackOff) {
59+
do {
60+
asm_volatile_pause();
61+
} while (++spinCount < spinCountTarget);
62+
spinCountTarget <<= 1;
63+
} else {
64+
++spinCount;
5865
asm_volatile_pause();
59-
} while (++spinCount < spinCountLog);
60-
spinCountLog <<= 1;
61-
#else
62-
++spinCount;
63-
asm_volatile_pause();
64-
#endif
66+
}
6567
} else {
6668
/* sleep override */
6769
std::this_thread::sleep_for(delta);

0 commit comments

Comments
 (0)