Created
November 17, 2012 07:09
-
-
Save ArtemGr/4093954 to your computer and use it in GitHub Desktop.
Nice priority of a Linux thread.
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 <iostream> // cout, cerr, endl | |
#include <memory> // shared_ptr | |
#include <sys/time.h> // setpriority | |
#include <sys/resource.h> // setpriority | |
/** | |
* Set low nice priority in the current Linux thread.\n | |
* Usage: \code auto&& restorePriority = ioNice(); \endcode. | |
*/ | |
static shared_ptr<void> ioNice (int priority = 19) { | |
shared_ptr<void> restorePriority; | |
#ifdef __linux__ | |
// Lower the I/O priority of the thread (cf. `man ionice`). | |
const auto tid = gettid(); | |
std::cout << "Setting *nice* priority of TID " << tid << " to " << priority << "." << std::endl; | |
errno = 0; const auto oldNicePriority = ::getpriority (PRIO_PROCESS, tid); | |
if (oldNicePriority == -1 && errno) std::cerr << "getpriority: " << ::strerror (errno) << std::endl; | |
if (::setpriority (PRIO_PROCESS, tid, priority)) std::cerr << "setpriority: " << ::strerror (errno) << std::endl; | |
restorePriority.reset ((void*) nullptr, [=](void*) { | |
std::cout << "Restoring *nice* priority of TID " << tid << " to " << oldNicePriority << "." << std::endl; | |
if (::setpriority (PRIO_PROCESS, tid, oldNicePriority)) std::cerr << "setpriority: " << ::strerror (errno) << std::endl; | |
}); | |
#endif | |
return restorePriority; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment