ThreadSchedule 4.1.0
Modern C++ thread management library
Loading...
Searching...
No Matches
thread_affinity.hpp
Go to the documentation of this file.
1#pragma once
2
7
8#include "cpu_id.hpp"
9#include "detail/lifetime.hpp"
10
11#include <algorithm>
12#include <initializer_list>
13#include <utility>
14#include <vector>
15
16namespace threadschedule
17{
18
20{
21public:
23 thread_affinity() = default;
28 explicit thread_affinity(std::vector<cpu_id> cpus) : cpus_(std::move(cpus))
29 {
30 normalize();
31 }
32
37 thread_affinity(std::initializer_list<cpu_id> cpus) : cpus_(cpus)
38 {
39 normalize();
40 }
41
46 void
48 {
49 if (contains(cpu))
50 return;
51 cpus_.push_back(cpu);
52 std::sort(cpus_.begin(), cpus_.end());
53 }
54
59 void
61 {
62 cpus_.erase(std::remove(cpus_.begin(), cpus_.end(), cpu), cpus_.end());
63 }
64
66 void
67 clear() noexcept
68 {
69 cpus_.clear();
70 }
71
76 [[nodiscard]] auto
77 contains(cpu_id cpu) const noexcept -> bool
78 {
79 return std::binary_search(cpus_.begin(), cpus_.end(), cpu);
80 }
81
83 [[nodiscard]] auto
84 empty() const noexcept -> bool
85 {
86 return cpus_.empty();
87 }
88
90 [[nodiscard]] auto
91 cpus() const noexcept THREADSCHEDULE_LIFETIMEBOUND -> std::vector<cpu_id> const&
92 {
93 return cpus_;
94 }
95
96private:
97 void
98 normalize()
99 {
100 std::sort(cpus_.begin(), cpus_.end());
101 cpus_.erase(std::unique(cpus_.begin(), cpus_.end()), cpus_.end());
102 }
103
104 std::vector<cpu_id> cpus_;
105};
106
107} // namespace threadschedule
Validated CPU identifier.
Definition cpu_id.hpp:23
void remove_cpu(cpu_id cpu)
Remove a CPU from the affinity set.
thread_affinity(std::vector< cpu_id > cpus)
Construct from a list of CPUs.
thread_affinity(std::initializer_list< cpu_id > cpus)
Construct from an initializer list of CPUs.
thread_affinity()=default
Construct an empty affinity set (no CPU pinning requested).
auto contains(cpu_id cpu) const noexcept -> bool
Check whether a CPU is present in the affinity set.
void clear() noexcept
Remove all CPUs from the affinity set.
void add_cpu(cpu_id cpu)
Add a CPU to the affinity set.
auto empty() const noexcept -> bool
Return whether the affinity set is empty.
auto cpus() const noexcept THREADSCHEDULE_LIFETIMEBOUND -> std::vector< cpu_id > const &
Return the normalized sorted list of CPUs in the set.
Strongly-typed CPU index used by affinity-related APIs.
Optional compiler diagnostics for borrowed references and pointers.
#define THREADSCHEDULE_LIFETIMEBOUND
Definition lifetime.hpp:28
#define THREADSCHEDULE_OWNER
Definition lifetime.hpp:35