workqueue,中文稱其為工作隊列,是一個用於創建內核線程的接口,通過它創建的內核線程來執行內核其他模塊排列到隊列里的工作,創建的內核線程被稱為工作者線程。要理解工作隊列的實現,重點在於理解相關的三個數據結構的含義及關系。
1 表示工作隊列類型的數據結構:struct workqueue_struct
- /*
- * The externally visible workqueue abstraction is an array of
- * per-CPU workqueues:
- */
- struct workqueue_struct {
- struct cpu_workqueue_struct *cpu_wq; /*工作者線程數組*/
- struct list_head list; /*連接工作隊列類型的鏈表*/
- const char *name; /*工作者線程的名稱*/
- int singlethread; /*是否創建新的工作者線程,0表示采用默認的工作者線程event/n*/
- int freezeable; /* Freeze threads during suspend */
- int rt;
- #ifdef CONFIG_LOCKDEP
- struct lockdep_map lockdep_map;
- #endif
- };
內核中默認的工作隊列為:
- static struct workqueue_struct *keventd_wq __read_mostly;
其對應的工作者線程為:event/n 其中,n代表當前cpu中processor的個數。
2. 表示工作者線程的數據結構:struct cpu_workqueue_struct
- /*
- * The per-CPU workqueue (if single thread, we always use the first
- * possible cpu).
- */
- struct cpu_workqueue_struct {
- spinlock_t lock; /*因為工作者線程需要頻繁的處理連接到其上的工作,所以需要枷鎖保護*/
- struct list_head worklist;
- wait_queue_head_t more_work;
- struct work_struct *current_work; /*當前工作線程需要處理的工作*/
- struct workqueue_struct *wq; /*該工作者線程屬於那種類型的工作者隊列*/
- struct task_struct *thread; /*指向工作者線程的任務結構體*/
- } ____cacheline_aligned;
3. 表示工作的數據結構,即工作者線程處理的對象:struct work_struct
- struct work_struct {
- atomic_long_t data; /*工作處理函數func的參數*/
- #define WORK_STRUCT_PENDING 0 /* T if work item pending execution */
- #define WORK_STRUCT_STATIC 1 /* static initializer (debugobjects) */
- #define WORK_STRUCT_FLAG_MASK (3UL)
- #define WORK_STRUCT_WQ_DATA_MASK (~WORK_STRUCT_FLAG_MASK)
- struct list_head entry; /*連接工作的指針*/
- work_func_t func; /*工作處理函數*/
- #ifdef CONFIG_LOCKDEP
- struct lockdep_map lockdep_map;
- #endif
- };
再分析了以上三個對象后,重點掌握三者之間的關系。工作隊列類型,工作者線程以及工作三個數據對象之間的關系如圖所示。
workqueue的執行非常簡單,即在每次運行工作者線程的時候,去遍歷工作者線程對應的工作鏈表上的工作,逐一進行處理即可,從這里我們也可以猜到,工作隊列是沒有優先級的,基本按照FIFO的方式進行處理。
轉自:http://blog.csdn.net/ustc_dylan/article/details/6371229