Linux C++ 设置进程/线程到最大优先级

先决条件:

#ifdef _WIN32
#include <Windows.h>
#else
#include <sched.h>
#include <pthread.h>
#include <sys/sysinfo.h>
#include <sys/resource.h>
#include <sys/file.h>
#endif

设置线程到最大优先级别

void SetThreadPriorityToMaxLevel() noexcept {
#ifdef _WIN32
    SetThreadPriority(GetCurrentProcess(), THREAD_PRIORITY_TIME_CRITICAL);
#else
    /* ps -eo state,uid,pid,ppid,rtprio,time,comm */
    struct sched_param param_;
    param_.sched_priority = sched_get_priority_max(SCHED_FIFO); // SCHED_RR
    pthread_setschedparam(pthread_self(), SCHED_FIFO, &param_);
#endif
}

进程设置为RT(实时)模式

bool WriteAllBytes(const char* path, const void* data, int length) noexcept {
    if (NULL == path || length < 0) {
        return false;
    }

    if (NULL == data && length != 0) {
        return false;
    }

    FILE* f = fopen(path, "wb+");
    if (NULL == f) {
        return false;
    }

    if (length > 0) {
        fwrite((char*)data, length, 1, f);   
    }

    fflush(f);
    fclose(f);
    return true;
}

void SetProcessPriorityToMaxLevel() noexcept {
#ifdef _WIN32
    SetPriorityClass(GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
#else
    char path_[260];
    snprintf(path_, sizeof(path_), "/proc/%d/oom_adj", getpid());

    char level_[] = "-17";
    WriteAllBytes(path_, level_, sizeof(level_));

    /* Processo pai deve ter prioridade maior que os filhos. */
    setpriority(PRIO_PROCESS, 0, -20);

    /* ps -eo state,uid,pid,ppid,rtprio,time,comm */
    struct sched_param param_;
    param_.sched_priority = sched_get_priority_max(SCHED_FIFO); // SCHED_RR
    sched_setscheduler(getpid(), SCHED_RR, &param_);
#endif
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值