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

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

template <class T>
static inline T RandomizeSleepTime(T t) noexcept {
    static TAtomic counter = 0;
    const T rndNum = IntHash((T)AtomicIncrement(counter));

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

//arbitrary values
#define MIN_SLEEP_TIME 500
#define 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();
    }
}