Linux工作队列
今天刚好要用到工作队列,在网上搜了一圈,感觉讲的比较简单,很多细节的东西没有描述清楚,因此决定写篇文章记录下,便于以后查找。
Linux中的等待队列有两种,一种是普通的work queue,还有一种是可以给定延时多久以后执行的work queue,相比普通的来说,其多了延时时间这个参数,下面将具体介绍下应该如何使用这两种work queue。
1. 普通workqueue的使用
重要结构体:
structwork_struct {
atomic_long_t data;
struct list_head entry;
work_func_t func;
#ifdefCONFIG_LOCKDEP
struct lockdep_map lockdep_map;
#endif
};
1) 需自己创建队列头
struct my_work {
void * data; //可以存放一些私有数据
struct work_struct work;
} my_work;
structworkqueue_struct *mywork_wq //创建工作队列
mywork_wq= alloc_workqueue("mywork", 0, 0);
static void _func(struct work_struct *work)
{
}
INIT_WORK(my_work.work, _func); //初始化工作
queue_work(mywork_wq, &my_work.work) //提交工作到mywork_wq队列
创建工作队列还有如下API:
create_workqueue(name)
create_freezable_workqueue(name)
alloc_ordered_workqueue(fmt, flags, args...)
create_singlethread_workqueue(name)
销毁工作队列:
destroy_workqueue(struct workqueue_struct *wq);
2) 直接挂载到全局队列头system_wq中
该方法比方法1简单,无需创建队列头,直接挂在system_wq上,优点是使用方法更加简单(省略1中红色斜体部分),缺点是在system_wq队列中如果积累了大量的work(系统负载较高时),work的响应速度下降。
使用schedule_work(&my_work.work)将任务提交到任务队列system_wq上。
2. 延时workqueue的使用
延时workqueue与普通workqueue的使用方法类似,这边就不详细介绍了,下面列一下延时队列中的一些重要结构体和函数
structdelayed_work {
struct work_struct work;
struct timer_list timer;
/* target workqueue and CPU ->timeruses to queue ->work */
struct workqueue_struct *wq;
int cpu;
};
INIT_DELAYED_WORK(_work, _func)
static inline bool schedule_delayed_work(struct delayed_work *dwork,
unsigned long delay)
static inline bool cancel_delayed_work(struct delayed_work *dwork);