vulp  2.3.0
realtime.h
Go to the documentation of this file.
1 // SPDX-License-Identifier: Apache-2.0
2 // Copyright 2022 Stéphane Caron
3 
4 #pragma once
5 
6 #include <sched.h>
7 #include <sys/mman.h>
8 
9 #include <stdexcept>
10 
11 #ifdef __APPLE__
12 #include <spdlog/spdlog.h>
13 #endif
14 
15 namespace vulp::utils {
16 
23 inline void configure_cpu(int cpu) {
24 #ifndef __APPLE__
25  constexpr int kPid = 0; // this thread
26  cpu_set_t cpuset = {};
27  CPU_ZERO(&cpuset);
28  CPU_SET(cpu, &cpuset);
29  if (::sched_setaffinity(kPid, sizeof(cpu_set_t), &cpuset) < 0) {
30  throw std::runtime_error("Error setting CPU affinity");
31  }
32 #else
33  spdlog::warn("[configure_cpu] This function does nothing on macOS");
34 #endif
35 }
36 
45 inline void configure_scheduler(int priority) {
46 #ifndef __APPLE__
47  constexpr int kPid = 0; // this thread
48  struct sched_param params = {};
49  params.sched_priority = priority;
50  if (::sched_setscheduler(kPid, SCHED_RR, &params) < 0) {
51  throw std::runtime_error(
52  "Error setting realtime scheduler, try running as root (use sudo)");
53  }
54 #else
55  spdlog::warn("[configure_scheduler] This function does nothing on macOS");
56 #endif
57 }
58 
63 inline bool lock_memory() {
64  return (::mlockall(MCL_CURRENT | MCL_FUTURE) >= 0);
65 }
66 
67 } // namespace vulp::utils
Utility functions.
Definition: __init__.py:1
void configure_scheduler(int priority)
Configure the scheduler policy to round-robin for this thread.
Definition: realtime.h:45
void configure_cpu(int cpu)
Set the current thread to run on a given CPU core.
Definition: realtime.h:23
bool lock_memory()
Lock all memory to RAM so that the kernel doesn't page it to swap.
Definition: realtime.h:63