Skip to content

Instantly share code, notes, and snippets.

@DavidYKay
Last active August 13, 2022 13:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DavidYKay/4fafa1c204e9dbefef0ee3aa6d4ad180 to your computer and use it in GitHub Desktop.
Save DavidYKay/4fafa1c204e9dbefef0ee3aa6d4ad180 to your computer and use it in GitHub Desktop.
Run an infinite loop at max/FIFO thread priority. OS: Linux, w/ pthread.
#include <pthread.h>
#include <sched.h>
#include <iostream>
void infLoop() {
int i = 0;
while (true) {
i = (i + 1) % 1024;
}
}
void set_realtime_priority() {
int ret;
// We'll operate on the currently running thread.
pthread_t this_thread = pthread_self();
// struct sched_param is used to store the scheduling priority
struct sched_param params;
// We'll set the priority to the maximum.
params.sched_priority = sched_get_priority_max(SCHED_FIFO);
std::cout << "Trying to set thread realtime prio = " << params.sched_priority << std::endl;
// Attempt to set thread real-time priority to the SCHED_FIFO policy
ret = pthread_setschedparam(this_thread, SCHED_FIFO, &params);
if (ret != 0) {
// Print the error
std::cout << "Unsuccessful in setting thread realtime prio" << std::endl;
return;
}
// Now verify the change in thread priority
int policy = 0;
ret = pthread_getschedparam(this_thread, &policy, &params);
if (ret != 0) {
std::cout << "Couldn't retrieve real-time scheduling paramers" << std::endl;
return;
}
// Check the correct policy was applied
if(policy != SCHED_FIFO) {
std::cout << "Scheduling is NOT SCHED_FIFO!" << std::endl;
} else {
std::cout << "SCHED_FIFO OK" << std::endl;
}
// Print thread scheduling priority
std::cout << "Thread priority is " << params.sched_priority << std::endl;
std::cout << "Looping!";
infLoop();
}
int main() {
set_realtime_priority();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment