1+ /* *
2+ * @file thread.hpp
3+ * @brief Various thread utilities
4+ *
5+ *
6+ */
7+
8+ #pragma once
9+
10+ #include " cpputils2/common/types.hpp"
11+
12+ #include < pthread.h>
13+ #include < sched.h>
14+ #include < sys/syscall.h>
15+ #include < unistd.h>
16+
17+ #include < cassert>
18+ #include < expected>
19+ #include < thread>
20+
21+ namespace CppUtils2
22+ {
23+ struct ThreadConfig
24+ {
25+ int policy;
26+ int priority;
27+ };
28+
29+ struct RealTimeThreadConfig : public ThreadConfig
30+ {
31+ RealTimeThreadConfig ()
32+ {
33+ policy = SCHED_FIFO;
34+ priority = 99 ;
35+ }
36+ };
37+
38+ struct BestEffortThreadConfig : public ThreadConfig
39+ {
40+ BestEffortThreadConfig ()
41+ {
42+ policy = SCHED_OTHER;
43+ priority = 0 ;
44+ }
45+ };
46+
47+ Result set_thread_sched_policy (std::thread &thread, const int policy, const int priority)
48+ {
49+ struct sched_param param;
50+ param.sched_priority = priority;
51+
52+ // ensure that native_handler() is a pthread_t
53+ assert (typeid (thread.native_handle ()) == typeid (pthread_t ));
54+
55+ int ret = pthread_setschedparam (thread.native_handle (), policy, ¶m);
56+ if (ret != 0 )
57+ {
58+ return Result::RET_ERROR;
59+ }
60+
61+ return Result::RET_OK;
62+ }
63+
64+ Result set_thread_sched_policy (std::thread &thread, const ThreadConfig &config)
65+ {
66+ return set_thread_sched_policy (thread, config.policy , config.priority );
67+ }
68+
69+ std::expected<ThreadConfig, Result> get_thread_sched_policy (std::thread &thread)
70+ {
71+ int policy;
72+ struct sched_param param;
73+
74+ // ensure that native_handler() is a pthread_t
75+ assert (typeid (thread.native_handle ()) == typeid (pthread_t ));
76+ ThreadConfig config;
77+ int ret = pthread_getschedparam (thread.native_handle (), &config.policy , ¶m);
78+ config.priority = param.sched_priority ;
79+ Result ret_result = Result::RET_ERROR;
80+ if (ret != 0 )
81+ {
82+ return std::unexpected (ret_result);
83+ }
84+
85+ return config;
86+ }
87+
88+ }
0 commit comments