aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/actors/util/affinity.cpp
blob: cc1b6e70ec85db239e3f54f91c973f802b5af0f1 (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
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
#include "affinity.h"

#ifdef _linux_
#include <sched.h>
#endif

class TAffinity::TImpl {
#ifdef _linux_
    cpu_set_t Mask;
#endif
public:
    TImpl() {
#ifdef _linux_
        int ar = sched_getaffinity(0, sizeof(cpu_set_t), &Mask);
        Y_VERIFY_DEBUG(ar == 0);
#endif
    }

    explicit TImpl(const ui8* cpus, ui32 size) {
#ifdef _linux_
        CPU_ZERO(&Mask);
        for (ui32 i = 0; i != size; ++i) {
            if (cpus[i]) {
                CPU_SET(i, &Mask);
            }
        }
#else
        Y_UNUSED(cpus);
        Y_UNUSED(size);
#endif
    }

    void Set() const {
#ifdef _linux_
        int ar = sched_setaffinity(0, sizeof(cpu_set_t), &Mask);
        Y_VERIFY_DEBUG(ar == 0);
#endif
    }

    operator TCpuMask() const {
        TCpuMask result;
#ifdef _linux_
        for (ui32 i = 0; i != CPU_SETSIZE; ++i) {
            result.Cpus.emplace_back(CPU_ISSET(i, &Mask));
        }
        result.RemoveTrailingZeros();
#endif
        return result;
    }

};

TAffinity::TAffinity() {
}

TAffinity::~TAffinity() {
}

TAffinity::TAffinity(const ui8* x, ui32 sz) {
    if (x && sz) {
        Impl.Reset(new TImpl(x, sz));
    }
}

TAffinity::TAffinity(const TCpuMask& mask) {
    if (!mask.IsEmpty()) {
        static_assert(sizeof(ui8) == sizeof(mask.Cpus[0]));
        const ui8* x = reinterpret_cast<const ui8*>(&mask.Cpus[0]);
        const ui32 sz = mask.Size();
        Impl.Reset(new TImpl(x, sz));
    }
}

void TAffinity::Current() {
    Impl.Reset(new TImpl());
}

void TAffinity::Set() const {
    if (!!Impl) {
        Impl->Set();
    }
}

bool TAffinity::Empty() const {
    return !Impl;
}

TAffinity::operator TCpuMask() const {
    if (!!Impl) {
        return *Impl;
    }
    return TCpuMask();
}