如何使用queue_delayed_work函数
本文转自如何使用queue_delayed_work函数
1. delayed_workqueue主要用在需要延迟处理任务的驱动中,这些驱动的特性主要是不能使用中断。
delayed_workqueue的使用步骤如下:
1) 定义workqueue要做的delayed工作:struct delayed_work mdelayed_work;
2) 定义workqueue: struct workqueue_struct *mworkqueue;
3) 初始化workqueue:INIT_DELAYED_WORK(mworkqueue, mdelayed_work);
4) 创建线程queue并加以名字:mworkqueue = create_singlethread_workqueue("myqueue");
5) 运行queue:queue_delayed_work(mworkqueue, mdelayed_work, delay_time);
注:如果要实现循环实行任务,可以在在delayed_work中将delayed_workqueue再次添加到queue中,即在delayed_work中调用queue_delayed_work。
1) 定义workqueue要做的delayed工作:struct delayed_work mdelayed_work;
2) 定义workqueue: struct workqueue_struct *mworkqueue;
3) 初始化workqueue:INIT_DELAYED_WORK(mworkqueue, mdelayed_work);
4) 创建线程queue并加以名字:mworkqueue = create_singlethread_workqueue("myqueue");
5) 运行queue:queue_delayed_work(mworkqueue, mdelayed_work, delay_time);
注:如果要实现循环实行任务,可以在在delayed_work中将delayed_workqueue再次添加到queue中,即在delayed_work中调用queue_delayed_work。
2.举例分析:
#include <linux/sched.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/workqueue.h>
#include <linux/proc_fs.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/kernel.h>
struct delayed_work mdwq;
struct workqueue_struct *mwq;
void delay_work_func(struct work_struct *work)
{
int i;
printk(KERN_INFO "%s:%d\n",__FUNCTION__,__LINE__);
for (i = 0; i < 3; i++) {
printk(KERN_ERR "%s:i=%d\n",__FUNCTION__,i);
msleep(3000);
}
}
static int __init delay_work_init(void)
{
int ret;
int i;
mwq = create_workqueue("my workqueue");
if (!mwq) {
printk(KERN_ERR "Create workqueue failed!\n");
return 1;
}
printk(KERN_INFO "Create workqueue successful!\n");
INIT_DELAYED_WORK(&mdwq, delay_work_func);
ret = queue_delayed_work(mwq, &mdwq, 3000);
printk(KERN_INFO "first ret=%d!\n", ret);
for (i = 0; i < 3; i++) {
printk(KERN_INFO "%s:ret=%d,i=%d\n",__FUNCTION__,ret, i);
msleep(1000);
}
ret = queue_delayed_work(mwq, &mdwq, 0);
printk(KERN_INFO "second ret=%d!\n", ret);
return 0;
}
static void __exit delay_work_exit(void)
{
int ret;
ret = cancel_delayed_work(&mdwq);
flush_workqueue(mwq);
destroy_workqueue(mwq);
printk(KERN_INFO "Exit! ret=%d\n", ret);
}
module_init(delay_work_init);
module_exit(delay_work_exit);
MODULE_LICENSE("GPL");
运行结果:
kernel: Create workqueue successful!
kernel: first ret=1!
kernel: delay_work_init:ret=1,i=0
kernel: delay_work_init:ret=1,i=1
kernel: delay_work_init:ret=1,i=2
kernel: second ret=0!
kernel: Exit! ret=1
从例子可以看出当工作队列还在执行该任务,调用queue_delayed_work()返回1,否则返回0。
主线程mwq将任务添加到工作队列后,使得工作队列在延迟delay后执行函数delay_work_func(),而mwq线程继续执行;
转载请注明本文转自如何使用queue_delayed_work函数,谢谢。