以低优先级运行线程

时间:2018-09-18 09:30:46

标签: c linux multithreading pthreads scheduler

我已经使用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");

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

2 个答案:

答案 0 :(得分: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.

答案 1 :(得分:0)

pthread_create的手册页中

  

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

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

param.sched_priority = 0;

并且在pthread_setschedparam的手册页中

  

int pthread_setschedparam (pthread_t线程,int策略,       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]

并针对priority检查PID

还请阅读有关Linux线程调度优先级的@paxdiablo答案here