File: ThreadPrioUnix.cpp

package info (click to toggle)
soapyremote 0.5.2-4.1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 608 kB
  • sloc: cpp: 7,724; makefile: 13
file content (38 lines) | stat: -rw-r--r-- 1,079 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// Copyright (c) 2015-2015 Josh Blum
// SPDX-License-Identifier: BSL-1.0

#include "ThreadPrioHelper.hpp"
#include <cstring> //memset, strerror
#include <cerrno> //errno
#include <sched.h>

#ifdef __APPLE__
#include <thread>
#endif

std::string setThreadPrio(const double prio)
{
    //no negative priorities supported on this OS
    if (prio <= 0.0) return "";

    //determine priority bounds
    const int policy(SCHED_RR);
    const int maxPrio = sched_get_priority_max(policy);
    if (maxPrio < 0) return strerror(errno);
    const int minPrio = sched_get_priority_min(policy);
    if (minPrio < 0) return strerror(errno);

    //set realtime priority and prio number
    struct sched_param param;
    std::memset(&param, 0, sizeof(param));
    param.sched_priority = minPrio + int(prio * (maxPrio-minPrio));

#ifdef __APPLE__
    pthread_t tID = pthread_self();  // ID of this thread
    if (pthread_setschedparam(tID, policy, &param) != 0) return strerror(errno);
#else
    if (sched_setscheduler(0, policy, &param) != 0) return strerror(errno);
#endif

    return "";
}