Skip to content

Instantly share code, notes, and snippets.

@ArtemGr
Created November 17, 2012 07:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ArtemGr/4093954 to your computer and use it in GitHub Desktop.
Save ArtemGr/4093954 to your computer and use it in GitHub Desktop.
Nice priority of a Linux thread.
#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