工作队列的使用

  这里提供一下工作队列使用的例子,这里使用工作队列来循环打印一个消息。

#include <linux/module.h>
#include <linux/init.h>
#include <linux/workqueue.h>
#include <linux/delay.h>

static struct workqueue_struct *queue=NULL;
static struct work_struct work;
static struct delayed_work delay_work;
struct timer_list timer;
//#define SHARE_WORKQUEUE
#define CUSTOMIZE_WORKQUEUE
#define DELAY_WORKQUEUE

static void work_handler(struct work_struct *data)
{
	printk(KERN_ALERT"work handler function.\n");
#ifdef DELAY_WORKQUEUE
#ifdef SHARE_WORKQUEUE
	schedule_delayed_work(&delay_work,msecs_to_jiffies(2000));
#else
	queue_delayed_work(queue,&delay_work,msecs_to_jiffies(2000));
#endif
#endif
}
static void timer_function(unsigned long arg) 
{ 
	mod_timer(&timer, jiffies + 2*HZ);
#ifdef SHARE_WORKQUEUE
	schedule_work(&work);
#else
	queue_work(queue,&work);
#endif
} 
void time_init(void)
{
	init_timer(&timer);
	timer.data=100;
	timer.function=timer_function;
}
static int __init workqueue_init(void)
{

	int ret=0;
	printk(KERN_ALERT"%s\n",__FUNCTION__);
#ifdef CUSTOMIZE_WORKQUEUE
	queue=create_singlethread_workqueue("singlethread_workqueue");/*鍒涘缓涓€涓崟绾跨▼鐨勫伐浣滈槦鍒?/
	if (!queue)
	{
		printk(KERN_ALERT"create singlethread workqueue err!\n");
		ret=-1;
	}
#endif
#ifdef DELAY_WORKQUEUE
	INIT_DELAYED_WORK(&delay_work,work_handler);
	schedule_delayed_work(&delay_work,2*HZ);
#else
	INIT_WORK(&work,work_handler);
	time_init();
	add_timer(&timer);
#endif
	return ret;
}

static void __exit workqueue_exit(void)
{
	printk(KERN_ALERT"workqueue exit!\n");
#ifdef DELAY_WORKQUEUE
	cancel_delayed_work(&delay_work);
#else
	del_timer(&timer);
#endif
#ifdef CUSTOMIZE_WORKQUEUE
	destroy_workqueue(queue);
#endif
}
MODULE_LICENSE("GPL");
module_init(workqueue_init);
module_exit(workqueue_exit);

这里观察工作队列调度函数schedule_work,schedule_delayed_work,实际上是调用了queue_work和queue_delayed_work,这里的system_wq是内核已经创建好的工作队列,

如果该共享工作队列不能满足需要,可通过create_workqueue或者create_singlethread_workqueus(在一个核上创建)来创建一个工作队列。

static inline bool schedule_work(struct work_struct *work)
{
	return queue_work(system_wq, work);
}

static inline bool schedule_delayed_work(struct delayed_work *dwork,
                     unsigned long delay)
{
    return queue_delayed_work(system_wq, dwork, delay);
}

system_wq = alloc_workqueue("events", 0, 0);

INIT_DELAYED_WORK和INIT_WORK的区别就是,创建的工作可以延时一段时间再被调度。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值