hmbdc
simplify-high-performance-messaging-programming
Thread.hpp
1 #include "hmbdc/Copyright.hpp"
2 #pragma once
3 #include "hmbdc/os/Thread.hpp"
4 #include "hmbdc/Exception.hpp"
5 #include <pthread.h>
6 #include <string>
7 #include <thread>
8 
9 #include <stdexcept>
10 
11 
12 namespace hmbdc { namespace os {
13 
14 struct ThreadConfigException : std::runtime_error {
15  using std::runtime_error::runtime_error;
16 };
17 
18 void
19 configureCurrentThread(char const*threadName, unsigned long cpumask
20  , char const* schepolicy = "SCHED_OTHER", int priority = 0);
21 
22 void
23 setCurrrentThreadSched(char const* schepolicy, int priority);
24 
25 inline
26 void
27 configureCurrentThread(char const*threadName, unsigned long cpumask
28  , char const* schepolicy, int priority) {
29  int res0 = 0, res1 = 0;
30 #ifndef _QNX_SOURCE
31  if (cpumask && cpumask != 0xfffffffffffffffful) {
32  cpumask &= (1ul << std::thread::hardware_concurrency()) - 1ul;
33  if (cpumask != (1ul << std::thread::hardware_concurrency()) - 1ul) {
34  cpu_set_t mask;
35  CPU_ZERO(&mask);
36  for (unsigned long i = 0; i < sizeof(cpumask) * 8ul; ++i) {
37  if (cpumask & (1ul << i)) {
38  CPU_SET(i, &mask);
39  }
40  }
41  res0 = pthread_setaffinity_np(pthread_self(), sizeof(mask), &mask);
42  }
43  }
44 #endif
45  sched_param param = {0};
46  int policy = SCHED_RR;
47  if (std::string(schepolicy) == "SCHED_FIFO") {
48  policy = SCHED_FIFO;
49  }
50  else if (std::string(schepolicy) == "SCHED_RR") {
51  policy = SCHED_RR;
52  } else if (std::string(schepolicy) == "SCHED_IDLE") {
53 #ifndef _QNX_SOURCE
54  policy = SCHED_IDLE;
55 #else
56  policy = SCHED_SPORADIC;
57 #endif
58  }
59  else {
60  policy = SCHED_OTHER;
61 #ifndef _QNX_SOURCE
62  priority = 0;
63 #endif
64  }
65  param.sched_priority = priority;
66  res1 = pthread_setschedparam(pthread_self(), policy, &param);
67  int res2 = pthread_setname_np(pthread_self(), threadName);
68  if (res0 || res1 || res2)
69  HMBDC_THROW(ThreadConfigException, "cpumask=" << cpumask << " pthread_setaffinity_np=" << res0
70  << " pthread_setschedparam=" << res1 << " pthread_setname_np=" << res2);
71 }
72 
73 inline
74 void
75 setCurrrentThreadSched(char const* schepolicy, int priority) {
76 #ifndef _QNX_SOURCE
77  sched_param param = {0};
78  int policy = SCHED_RR;
79  if (std::string(schepolicy) == "SCHED_FIFO") {
80  policy = SCHED_FIFO;
81  }
82  else if (std::string(schepolicy) == "SCHED_RR") {
83  policy = SCHED_RR;
84  } else if (std::string(schepolicy) == "SCHED_IDLE") {
85  policy = SCHED_IDLE;
86  }
87  else {
88  policy = SCHED_OTHER;
89  priority = 0;
90  }
91  param.sched_priority = priority;
92  int res1 = pthread_setschedparam(pthread_self(), policy, &param);
93  if (res1)
94  HMBDC_THROW(ThreadConfigException, " sched_setscheduler=" << res1);
95 #endif
96 }
97 
98 }}
Definition: Thread.hpp:14
Definition: Base.hpp:12