workqueue原理和分析(轉)


workqueue,中文稱其為工作隊列,是一個用於創建內核線程的接口,通過它創建的內核線程來執行內核其他模塊排列到隊列里的工作,創建的內核線程被稱為工作者線程。要理解工作隊列的實現,重點在於理解相關的三個數據結構的含義及關系。

 
1 表示工作隊列類型的數據結構:struct workqueue_struct
  1. /*
  2.  * The externally visible workqueue abstraction is an array of
  3.  * per-CPU workqueues:
  4.  */
  5. struct workqueue_struct {
  6.     struct cpu_workqueue_struct *cpu_wq;   /*工作者線程數組*/
  7.     struct list_head list; /*連接工作隊列類型的鏈表*/
  8.     const char *name;        /*工作者線程的名稱*/          
  9.     int singlethread;         /*是否創建新的工作者線程,0表示采用默認的工作者線程event/n*/
  10.     int freezeable; /* Freeze threads during suspend */
  11.     int rt;
  12. #ifdef CONFIG_LOCKDEP
  13.     struct lockdep_map lockdep_map;
  14. #endif
  15. };

內核中默認的工作隊列為:

  1. static struct workqueue_struct *keventd_wq __read_mostly;

其對應的工作者線程為:event/n    其中,n代表當前cpu中processor的個數。

2. 表示工作者線程的數據結構:struct cpu_workqueue_struct

  1. /*
  2.  * The per-CPU workqueue (if single thread, we always use the first
  3.  * possible cpu).
  4.  */
  5. struct cpu_workqueue_struct {
  6.     spinlock_t lock;          /*因為工作者線程需要頻繁的處理連接到其上的工作,所以需要枷鎖保護*/
  7.     struct list_head worklist;
  8.     wait_queue_head_t more_work;
  9.     struct work_struct *current_work; /*當前工作線程需要處理的工作*/
  10.     struct workqueue_struct *wq;   /*該工作者線程屬於那種類型的工作者隊列*/
  11.     struct task_struct *thread;    /*指向工作者線程的任務結構體*/
  12. } ____cacheline_aligned;

3. 表示工作的數據結構,即工作者線程處理的對象:struct work_struct

  1. struct work_struct {
  2.     atomic_long_t data;       /*工作處理函數func的參數*/
  3. #define WORK_STRUCT_PENDING 0        /* T if work item pending execution */
  4. #define WORK_STRUCT_STATIC 1        /* static initializer (debugobjects) */
  5. #define WORK_STRUCT_FLAG_MASK (3UL)
  6. #define WORK_STRUCT_WQ_DATA_MASK (~WORK_STRUCT_FLAG_MASK)
  7.     struct list_head entry;        /*連接工作的指針*/
  8.     work_func_t func;              /*工作處理函數*/
  9. #ifdef CONFIG_LOCKDEP
  10.     struct lockdep_map lockdep_map;
  11. #endif
  12. };

再分析了以上三個對象后,重點掌握三者之間的關系。工作隊列類型,工作者線程以及工作三個數據對象之間的關系如圖所示。

workqueue的執行非常簡單,即在每次運行工作者線程的時候,去遍歷工作者線程對應的工作鏈表上的工作,逐一進行處理即可,從這里我們也可以猜到,工作隊列是沒有優先級的,基本按照FIFO的方式進行處理。

轉自:http://blog.csdn.net/ustc_dylan/article/details/6371229


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM