Android进程调度

线程在linux中的实现

Linux把所有的线程都当做进程来实现。内核并没有准备特别的调度算法或者或是定义特别的数据结构来表征线程。线程仅仅被视为一个与其他进程共享某些资源的进程。

进程优先级

Linux采用两种不同的优先级范围

  • nice值
    范围-20~19,默认值为0。nice值越大,优先级越
    高nice值的进程可以获得更多的处理器时间
    通过命令 ps -el 查看,NI这一列

system/core/libsystem/include/system/thread_defs.h

ANDROID_PRIORITY_LOWEST         =  19,

/* use for background tasks */
ANDROID_PRIORITY_BACKGROUND     =  10,

/* most threads run at normal priority */
ANDROID_PRIORITY_NORMAL         =   0,

/* threads currently running a UI that the user is interacting with */
ANDROID_PRIORITY_FOREGROUND     =  -2,

/* the main UI thread has a slightly more favorable priority */
ANDROID_PRIORITY_DISPLAY        =  -4,

/* ui service treads might want to run at a urgent display (uncommon) */
ANDROID_PRIORITY_URGENT_DISPLAY =  HAL_PRIORITY_URGENT_DISPLAY,

/* all normal video threads */
ANDROID_PRIORITY_VIDEO          = -10,

/* all normal audio threads */
ANDROID_PRIORITY_AUDIO          = -16,

/* service audio threads (uncommon) */
ANDROID_PRIORITY_URGENT_AUDIO   = -19,

/* should never be used in practice. regular process might not
* be allowed to use this level */
ANDROID_PRIORITY_HIGHEST        = -20,

  • 实时优先级
    范围0~99。实时优先级数值越高,优先级越
    实时进程的优先级都高于普通进程
    通过命令 ps -eo state,uid,pid,ppid,rtprio,time,comm 查看,RTPRIO这一列

时间片 time-slice

时间片是一个数值,它表明进程在被抢占前所能持续运行的时间。
nice值在Linux调度算法CFS(Completely Fair Scheduler)中被作为进程获得的处理器运行比的权重。

假设进程的调度周期是20ms,两个进程nice是分别是0和5,计算出比重是3/1,所获得处理器的时间片是15ms和5ms。假设这两个进程一个是10级,一个是15级,最后计算出来的时间也是15ms和5ms。

调度策略

  1. SCHED_NORMAL(Android叫SCHED_OTHER)分时调度策略
  2. SCHED_FIFO 实时调度策略,先到先服务
  3. SCHED_RR 实时调度策略,时间片轮转

Android API

Java
frameworks/base/core/java/android/os/Process.java

public static final native void setThreadPriority(int priority)
        throws IllegalArgumentException, SecurityException;

public static final native void setThreadPriority(int tid, int priority)
        throws IllegalArgumentException, SecurityException;

系统调用
bionic/libc/include/sys/resource.h

int setpriority(int, id_t, int);
  • 第一个参数 which 可选值为 PRIO_PROGRESS,表示设置进程;PRIO_PGROUP表示设置进程组;PRIO_USER表示user。
  • 第二个参数 who,根据第一个参数的不同,分别指向进程ID;进程组ID和user id。
  • 第三个参数 nice 值,从-20到19。是优先级的表示,越大表明越nicer,优先级越低。

参考资料:
Linux内核设计与实现 第三版.pdf 第四章

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容