以非常低的优先级运行线程

问题描述 投票:0回答:2

我使用pthread_create()在我的Linux应用程序中创建了一个线程。我想让这个线程以非常低的优先级运行,因为在同一个应用程序中有一些实时线程运行。以下是我在线程函数中的代码:

        pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
        pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);

        /* Trying to set lowest priority possible for this thread */
        param.sched_priority = 0;
        ret = pthread_setschedparam(pthread_self(), SCHED_IDLE, &param);
        if (!ret)
                printf("Successfully set sched policy of thread\n");

我想确认上面的代码是否合适。与其他实时线程相比,它是否保证我的线程不会被赋予更高的优先级。如果需要更改,请建议。仅供参考,代码在嵌入式平台上运行。

c linux multithreading pthreads scheduler
2个回答
0
投票

我假设您使用了默认Linux时间共享调度。因为你已经添加了param.sched_priority = 0;

为此,你可以检查Here

这表明

   SCHED_OTHER can be used at only static priority 0 (i.e., threads
   under real-time policies always have priority over SCHED_OTHER pro‐
   cesses).  SCHED_OTHER is the standard Linux time-sharing scheduler
   that is intended for all threads that do not require the special
   real-time mechanisms.
   The thread to run is chosen from the static priority 0 list based on
   a dynamic priority that is determined only inside this list.  The
   dynamic priority is based on the nice value (see below) and is
   increased for each time quantum the thread is ready to run, but
   denied to run by the scheduler.  This ensures fair progress among all
   SCHED_OTHER threads.

0
投票

来自pthread_create的手册页

int pthread_create(pthread_t * thread,const pthread_attr_t * attr,void *(* start_routine)(void *),void * arg);

您可以创建自己的属性并设置其属性,包括优先级。

param.sched_priority = 0;

并从pthread_setschedparam的手册页

int pthread_setschedparam(pthread_t thread,int policy,const struct sched_pa​​ram * param);

pthread_getschedparam()pthread_setschedparam()允许检索和设置多线程进程中各个线程的调度策略和调度参数。对于SCHED_FIFO和SCHED_RR,sched_pa​​ram结构中唯一需要的成员是优先级sched_priority。对于SCHED_OTHER,受影响的调度参数与实现有关。

如果pthread_setschedparam()函数失败,则不会更改目标线程的调度参数。

因此,它清楚地表明您可以设置和检索RRFIFO调度策略的调度参数。同样在SCHED_OTHER的情况下,它依赖于实现。

运行更改优先级的线程后,请运行命令并检查。例如,运行以下命令

ps -T -l [PID]

并查看关于priorityPID

另请阅读@paxdiablo回答here关于linux线程的调度优先级。

© www.soinside.com 2019 - 2024. All rights reserved.