假设我们有一个需要在后台执行的任务,比如读取某个文件并进行处理。由于这个任务可能会占用很长时间,如果直接在当前进程中执行可能会影响系统性能和响应速度。因此我们可以使用工作队列来实现异步执行。
1. 首先需要定义一个工作项,可以使用work_struct结构体来定义,例如:
struct work_struct example_work;
//2. 然后需要定义一个工作队列,可以使用workqueue_struct结构体来定义,例如:
//struct workqueue_struct *example_wq;
3. 接下来需要初始化工作项,可以使用INIT_WORK宏来初始化,例如:
INIT_WORK(&example_work, example_work_handler);
其中example_work_handler是一个函数指针,用于指向工作项的处理函数。
4. 然后需要将工作项推迟到稍后执行,可以使用schedule_work函数来实现,例如:
schedule_work(&example_work);
这样就可以将工作项example_work推迟到稍后执行了。
完整的代码示例如下:
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/workqueue.h>
//static struct workqueue_struct *example_wq;
static struct work_struct example_work;
static void example_work_handler(struct work_struct *work)
{
printk(KERN_INFO "Example work handler executed\n");
}
static int __init example_init(void)
{
printk(KERN_INFO "Example module initialized\n");
//example_wq = create_workqueue("example_wq");
//if (!example_wq) {
// return -ENOMEM;
//}
INIT_WORK(&example_work, example_work_handler);
schedule_work(&example_work);
return 0;
}
static void __exit example_exit(void)
{
cancel_work_sync(&example_work);
//destroy_workqueue(example_wq);
printk(KERN_INFO "Example module exited\n");
}
module_init(example_init);
module_exit(example_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Your Name");
MODULE_DESCRIPTION("Example");