Linux中工作队列使用
一. 背景:
内核版本2.5开发期间,设计了工作队列,用于解决:
Linux系统中延时一段时间执行一个任务、自定义函数。
二. API接口:
#include<linux/workqueue.h> //头文件
static struct workqueue_struct *test_wq; //声明一个工作队列
static struct delayed_work test_dwq; //声明一个延时工作描述实例
void delay_func(struct work_struct *work); //声明、实现一个工作队列延时处理函数
test_wq = create_workqueue("test_wq"); //初始化一个工作队列, init模块或probe函数添加
INIT_DELAYED_WORK(&test_dwq, delay_func);//延时工作任务初始化, init模块或probe函数添加
//参数1:工作队列,参数2:工作队列处理函数,参数3:延时时间
queue_delayed_work(test_wq, &test_dwq,delay); //初始化时向工作队列提交工作任务
cancel_delayed_work(test_wq); //取消工作对列中工作任务, exit函数添加
flush_workqueue(test_wq); //刷新工作对列, exit函数添加
destory_workqueue(test_wq); //工作队列销毁, exit函数添加
三.代码
#include <linux/workqueue.h>
static struct workqueue_struct *test_wq;
static struct delayed_work test_dwq;
static void delay_func(struct work_struct *work);
static void delay_func(struct work_struct *work){
printk(KERN_INFO "My name isdelay_func!\n);
//msecs_to_jiffies(5000)中5000即5000ms
//加上这句可以每隔5秒执行1次delay_func,若不添加执行1次
queue_delayed_work(test_wq, &test_dwq, msecs_to_jiffies(5000));
}
static int __init module_init(void){
test_wq = create_workqueue("test_wq");
if (!test_wq) {
printk(KERN_ERR "No memory for workqueue\n");
return 1;
}
printk(KERN_INFO "Create Workqueue successful!\n");
INIT_DELAYED_WORK(&test_dwq, delay_func); //在此找到延时工作任务:delay_func
queue_delayed_work(test_wq, &test_dwq,delay);
return 0;
}
static void __exit module_exit(void){
destory_workqueue(test_wq);
printk(KERN_INFO "Goodbay!\n");
}
引用:
https://www.cnblogs.com/youngerchina/archive/2011/12/23/5624642.html
https://blog.csdn.net/qq_30624591/article/details/90180946