Android nice在進程與線程調度中的作用

來源:互聯網
上載者:User

基本概念:

進程:電腦進行資源分派和高度的基本單位,是程式啟動並執行實體,也是線程的容器。

線程:是進程中實際執行的單元,是程式執行的最小單元,屬於一個進程。

一個進程可以擁有多個線程。


nice在進程調試中作用

在Android中,可以使用nice值來設定一個進程的優先順序,系統的調度器可以根據nice值來合理的調度進程,主要特點如下: 在Android中,nice的取值範圍為-20~19 在Android中,nice值的預設大小為0 在Android中,nice值越大,進程的優先順序越低,獲得的CPU調用機會就越少;nice值越高,進程的優先順序越高,獲得的CPU調用機會越多 在Android中,父進程fork出來的子進程nice值與父進程相同,你進程renice後,子進程的nice值不會改變


如何更改進程的nice值

Android中可用如下命令更改進程的nice值, usage: nice [-n PRIORITY] command [args...]

Run a command line at an increased or decreased scheduling priority.

Higher numbers make a program yield more CPU time, from -20 (highest
priority) to 19 (lowest).  By default processes inherit their parent's
niceness (usually 0).  By default this command adds 10 to the parent's
priority.  Only root can set a negative niceness level.


USAGE: renice [[-r] [-t TYPE] priority pids ...] [-g pid]

其中nice命令用於設定一個新建立的進程的優先順序,而renice命令用於更改已經建立的進程的優先順序,且這兩個命令都需要在root許可權下運行。


線程調度

在Android開發中,我們用的最多的是對於線程優先順序的控制,但在Android中,出現了兩種版本的線程優先順序控制:JAVA版本和Android版本,兩種版本的優先順序的主要差別如下: JAVA版本中的優先順序使用java.lang.Thread中的setPriority(int priority)和getPriority()設定和獲得線程的優先順序,其只包括三種類型的線程優先順序,屬於粗粒度控制,如下:

       public static final intMAX_PRIORITY = 10        public static final intMIN_PRIORITY = 5        public static final intMIN_PRIORITY = 1

  而Android版本中的線程優先順序使用android.os.Process類中的setThreadPriority(int priority)和getPriority()設定和  獲得線程的優先順序,其包括10中線程優先順序,相對於JAVA的屬於細粒度控制策略,如下:

   

  因此,在設定和擷取線程優先順序時,建議使用Android版本的API。 Android API的線程優先順序和JAVA原生API的優先順序是相對獨立的,比如使用 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND) 後,使用Java原生API,Thread.getPriority()得到的值不會改變。

由於上術第二點的差別,導致在分析ANR log時需要格外注意,在下面的ANR日誌資訊中,prio=5中proi的值對應的JAVA原生API的線程優先順序。而nice=-6中的nice表示的Android API版本的線程優先順序。

"main" prio=5 tid=1 NATIVE
  | group="main" sCount=1 dsCount=0 obj=0x41690f18 self=0x4167e650
  | sysTid=1765 nice=-6 sched=0/0 cgrp=apps handle=1074196888
  | state=S schedstat=( 0 0 0 ) utm=5764 stm=3654 core=2
  #00  pc 00022624  /system/lib/libc.so (__futex_syscall3+8)
  #01  pc 0000f054  /system/lib/libc.so (__pthread_cond_timedwait_relative+48)
  #02  pc 0000f0b4  /system/lib/libc.so (__pthread_cond_timedwait+64)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.