Fork me on GitHub

8/11/2012

[Linux] tweak process priority

在 debug vsync 的過程中,發現 CPU scheduling 對於 vsync accuracy 有影響,因此需要針對 vsync 所在的 process 修改其 process priority.
過程中發現利用 pthread 的 pthread_attr_t 並沒有辦法更動 priority,以下整理了網路上關於 process priority 的資料,目前猜測原因應該是:
Setting a priority under the default scheduling policy (SCHED_OTHER) isn't valid. The default Linux scheduling policy is SCHED_OTHER, which have no priority choice but a nice level to tweak inside the policy
由上面節錄的敘述中可以發現兩個陌生的東西:"scheduling policy" 和 "nice value". 來認識他們:
All Linux threads have one of the following scheduling policies:
  1. 'Normal' scheduling policies: ranging from 100 (highest priority) to 139 (lowest priority)
    SCHED_OTHER   the standard round-robin time-sharing policy;
    SCHED_BATCH   for "batch" style execution of processes; and
    SCHED_IDLE    for running very low priority background jobs.
    
  2. Real-time scheduling policies: ranging from 1 (lowest priority) to 99 (higest priority)
    SCHED_FIFO    a first-in, first-out policy
    SCHED_RR      a round-robin policy
    
Real-time scheduling 有什麼特性呢,簡單理解應該就是擁有比 Normal scheduling 更不可被搶佔的特性:
SCHED_FIFO can't be preempted (context switched to another process) unless another process of higher priority shows up in the execution queue.

SCHED_RR can be preempted by a time quantum (delay given to a process to execute).
一般的 process 沒有特別指定 default 應該都是 SCHED_OTHER 所以沒辦法透過 pthread_attr_t 設定其 priority,不過還有另外一個方法就是使用其 nice value.
Conventional process's static priority = (120 + Nice value)
因為 Normal scheduling policies 的 priority range 是從 100 ~ 139,那麼從上面可以推得,nice value 的 range 是 -20(highest priority) ~ 19(lowest priority).
至於設定 nice value 的方式似乎不只一種,經過試驗,setpriority 這個 function 是有效的。

Ref

  1. How to increase thread priority in pthreads?
  2. how to increase the priority of a child pthread relative to the parent thread
  3. Understanding Linux CPU scheduling priority
-- EOF --

No comments:

Post a Comment