| 1 | // For license of this file, see <project-root-folder>/LICENSE.md. |
| 2 | |
| 3 | #include "miscellaneous/thread.h" |
| 4 | |
| 5 | #include "definitions/definitions.h" |
| 6 | |
| 7 | #include <QThread> |
| 8 | |
| 9 | #if defined(Q_OS_LINUX) |
| 10 | #include <sched.h> |
| 11 | #include <sys/resource.h> |
| 12 | #include <unistd.h> |
| 13 | #endif |
| 14 | |
| 15 | // Returns the thread ID of the caller. |
| 16 | qlonglong getThreadID() { |
| 17 | #if defined(Q_OS_LINUX) |
| 18 | return qlonglong(gettid()); |
| 19 | #else |
| 20 | return qlonglong(QThread::currentThreadId()); |
| 21 | #endif |
| 22 | } |
| 23 | |
| 24 | #if defined(Q_OS_LINUX) |
| 25 | // On Linux QThread priorities do nothing with the default scheduler SCHED_OTHER. |
| 26 | // |
| 27 | // Set the nice value manually in this case until Qt supports nice values. |
| 28 | void setThreadPriority(Priority prio) { |
| 29 | int current_policy = sched_getscheduler(0); |
| 30 | |
| 31 | if (current_policy != -1) { |
| 32 | // If the current scheduling policy is neither of these the QThread priority should be working. |
| 33 | if (current_policy != SCHED_BATCH && current_policy != SCHED_OTHER) { |
| 34 | return; |
| 35 | } |
| 36 | |
| 37 | // Set the scheduler to SCHED_BATCH if needed, indicating that this process is non-interactive. |
| 38 | if (current_policy == SCHED_OTHER) { |
| 39 | struct sched_param p = {0}; |
| 40 | |
| 41 | if (sched_setscheduler(0, SCHED_BATCH, &p) != 0) { |
| 42 | qDebugNN << "Setting the scheduler to SCHED_BATCH for thread" << QUOTE_W_SPACE(getThreadID()) |
| 43 | << "failed with error" << QUOTE_W_SPACE_DOT(errno); |
| 44 | // We can still try to set the nice value. |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | errno = 0; // Clear errno since -1 is a legitimate return value. |
| 49 | |
| 50 | int current_priority = getpriority(PRIO_PROCESS, 0); |
| 51 | |
| 52 | if (errno != 0) { |
| 53 | qDebugNN << "Getting the priority for thread" << QUOTE_W_SPACE(getThreadID()) << "failed with error" |
| 54 | << QUOTE_W_SPACE_DOT(errno); |
| 55 | } |
| 56 | else { |
| 57 | if (current_priority != prio) { |
| 58 | setpriority(PRIO_PROCESS, 0, prio); |
| 59 | |
| 60 | if (errno != 0) { |
| 61 | qDebugNN << "Setting the priority for thread" << QUOTE_W_SPACE(getThreadID()) << "failed with error" |
| 62 | << QUOTE_W_SPACE_DOT(errno); |
| 63 | } |
| 64 | } |
| 65 | } |
| 66 | } |
| 67 | else { |
| 68 | qDebugNN << "Getting the priority for thread" << QUOTE_W_SPACE(getThreadID()) << "failed with error" |
| 69 | << QUOTE_W_SPACE_DOT(errno); |
| 70 | } |
| 71 | } |
| 72 | #endif |