1+ #pragma once
2+
3+ #include " cpputils2/common/types.hpp"
4+
5+ #include < cassert>
6+ #include < cstdint>
7+ #include < expected>
8+ #include < pthread.h>
9+ #include < sched.h>
10+ #include < sys/syscall.h>
11+ #include < unistd.h>
12+
13+ #include < span>
14+
15+ namespace CppUtils2
16+ {
17+
18+ // (yangosoft) As man 2 page says, this is a generic structure for scheduling attributes
19+ struct sched_attr
20+ {
21+ uint32_t size; /* Size of this structure */
22+ uint32_t sched_policy = 0 ; /* Policy (SCHED_*) */
23+ uint64_t sched_flags = 0 ; /* Flags */
24+ int32_t sched_nice = 0 ; /* Nice value (SCHED_OTHER,
25+ SCHED_BATCH) */
26+ uint32_t sched_priority = 0 ; /* Static priority (SCHED_FIFO,
27+ SCHED_RR) */
28+ /* Remaining fields are for SCHED_DEADLINE */
29+ uint64_t sched_runtime = 0 ;
30+ uint64_t sched_deadline = 0 ;
31+ uint64_t sched_period = 0 ;
32+
33+ sched_attr () : size(sizeof (sched_attr)) {}
34+ };
35+
36+ int32_t sched_getattr (pid_t pid, sched_attr *attr, unsigned int size, unsigned int flags = 0 )
37+ {
38+ return syscall (SYS_sched_getattr, pid, attr, size, flags);
39+ }
40+
41+ int32_t sched_setattr (pid_t pid, const sched_attr *attr, uint32_t flags = 0 )
42+ {
43+ return syscall (SYS_sched_setattr, pid, attr, flags);
44+ }
45+
46+ std::expected<Result, int32_t > set_self_attributes (const sched_attr *attr)
47+ {
48+ pid_t me = getpid ();
49+ int flags = 0 ;
50+
51+ int32_t ret = sched_setattr (me, attr, flags);
52+
53+ if (ret != 0 )
54+ {
55+ return std::unexpected (ret);
56+ }
57+
58+ return Result::RET_OK;
59+ }
60+
61+ std::expected<Result, int32_t > set_process_core_affinity (pid_t pid, const cpu_set_t *mask)
62+ {
63+ int ret = sched_setaffinity (pid, sizeof (cpu_set_t ), mask);
64+ if (ret != 0 )
65+ {
66+ return std::unexpected (errno);
67+ }
68+ return Result::RET_OK;
69+ }
70+
71+ std::expected<Result, int32_t > set_self_core_affinity (const cpu_set_t *mask)
72+ {
73+ return set_process_core_affinity (getpid (), mask);
74+ }
75+
76+ std::expected<Result, int32_t > set_process_core_affinity (pid_t pid, const std::span<uint32_t , std::dynamic_extent> &mask)
77+ {
78+
79+ cpu_set_t cpuset;
80+ CPU_ZERO (&cpuset);
81+ for (auto core : mask)
82+ {
83+ CPU_SET (core, &cpuset);
84+ }
85+
86+ return set_process_core_affinity (pid, &cpuset);
87+ }
88+
89+ std::expected<Result, int32_t > set_self_core_affinity (const std::span<uint32_t , std::dynamic_extent> &mask)
90+ {
91+ return set_process_core_affinity (getpid (), mask);
92+ }
93+
94+ } // namespace CppUtils2
0 commit comments