linux工作队列
這里對Linux的工作隊列(work_queue)不做深層次的挖掘,只對如何使用它以及一些簡單的結構做簡單地介紹。
Linux源代碼(3.0.8)中和工作隊列(work_queue)相關的結構主要在
include/linux/workqueue.h這個頭文件中,這里就不摘抄了。這里就直接給出例子代碼,在結合稍作解釋:
#include <linux/module.h> #include <linux/init.h> #include <linux/workqueue.h>static struct work_struct work;
static void work_handler(struct work_struct *data)
{
printk(“just a demo for work queue.\n”);
}
static int __init workqueue_init(void)
{
printk(“init work queue demo.\n”);
INIT_WORK(&work, work_handler);
schedule_work(&work);
return 0;
}
static void __exit workqueue_exit(void)
{
printk(“exit work queue demo.\n”);
}
MODULE_LICENSE(“GPL”);
MODULE_AUTHOR(“zhuqinggooogle@gmail.com”);
module_init(workqueue_init);
module_exit(workqueue_exit);
一個簡單的工作隊列(work_queue)的演示就完成了。我們來編譯后,insmod到系統看看:
/mnt/3520d $ insmod hi_work_queue.ko
init work queue demo
just a demo for work queue.
從系統中rmmod看一下:
/mnt/3520d $ rmmod hi_work_queue
exit work queue demo.
如果你對Linux的工作隊列(work_queue)有稍微的了解,你看到這里會提問,“我們的工作隊列項提交到了哪個工作隊列線程上面呢?”,這就得從
schedule_work函數入手??匆幌缕?**
* schedule_work - put work task in global workqueue
* @work: job to be done
*
* Returns zero if @work was already on the kernel-global workqueue and
* non-zero otherwise.
*
* This puts a job in the kernel-global workqueue if it was not already
* queued and leaves it in the same position on the kernel-global
* workqueue otherwise.
*/
int schedule_work(struct work_struct *work)
{
return queue_work(system_wq, work);
}
扯到
這個全局變量,我們來看看他到底是什么。在
kernel/workqueue.c這個文件的底部給出了定義:
system_wq = alloc_workqueue(“events”, 0, 0);
看到這就清楚了,剛才是把工作隊列項提交了默認的工作線程events上的。那我們自己可以創建一個工作隊列線程嗎?可以把自己的工作隊列項提交到上面嗎?當然,可以。下面給出一個demo代碼:
#include <linux/module.h> #include <linux/init.h> #include <linux/workqueue.h> static struct workqueue_struct *queue = NULL; static struct work_struct work; static void work_handler(struct work_struct *data) { printk("just a demo for work queue.\n"); } static int __init workqueue_init(void) { queue = create_singlethread_workqueue("workqueue demo");if (!queue) return -1; printk("init work queue demo.\n");INIT_WORK(&work, work_handler); queue_work("queue", &work); return 0; } static void __exit workqueue_exit(void) { printk("exit work queue demo.\n");destroy_workqueue(queue); } MODULE_LICENSE("GPL"); MODULE_AUTHOR("zhuqinggooogle@gmail.com"); module_init(workqueue_init); module_exit(workqueue_exit);我們來insmod看一下:
/mnt/3520d insmodhiworkqueue.koinitworkqueuedemo.justademoforworkqueue./mnt/3520d
/mnt/3520d $ ps | grep “workqueue demo”
728 root 0 SW< [workqueue demo]
你會發現多了一個內核線程workqueue demo,這就是我們代碼中自己創建的。
總結
- 上一篇: Android Protect-0.lu
- 下一篇: win11-vscode-wsl2 学习