Last active
August 13, 2022 13:11
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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, ¶ms); | |
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, ¶ms); | |
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