aboutsummaryrefslogtreecommitdiffstats
path: root/util/system/spin_wait.cpp
blob: ba1252911104b9675b995c229b78886795706fa3 (plain) (blame)
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
#include "spin_wait.h"
#include "yield.h"
#include "compat.h"
#include "spinlock.h"

#include <util/digest/numeric.h>
#include <util/generic/utility.h>

#include <atomic>

namespace {
    unsigned RandomizeSleepTime(unsigned t) noexcept {
        static std::atomic<unsigned> counter = 0;
        const unsigned rndNum = IntHash(++counter);

        return (t * 4 + (rndNum % t) * 2) / 5;
    }

    //arbitrary values
    constexpr unsigned MIN_SLEEP_TIME = 500;
    constexpr unsigned MAX_SPIN_COUNT = 0x7FF;
}

TSpinWait::TSpinWait() noexcept
    : T(MIN_SLEEP_TIME)
    , C(0)
{
}

void TSpinWait::Sleep() noexcept {
    ++C;

    if (C == MAX_SPIN_COUNT) {
        ThreadYield();
    } else if ((C & MAX_SPIN_COUNT) == 0) {
        usleep(RandomizeSleepTime(T));

        T = Min<unsigned>(T * 3 / 2, 20000);
    } else {
        SpinLockPause();
    }
}