您的位置:首页 > 运维架构 > Linux

Linux Kernel 学习笔记14:工作队列

2017-07-05 19:48 375 查看
(本章基于:Linux-3.13.0-32)

工作队列是一种将任务推后执行的形式。它把推后的任务交由一个内核线程去执行。此任务运行与进程上下文,它允许重新调度甚至是睡眠。因此工作队列也常用于中断分层设计模型中的下半部分。

数据结构

<linux/workqueue.h>

工作队列结构:

struct workqueue_struct {
struct cpu_workqueue_struct *cpu_wq;
struct list_head list;
const char *name; /*workqueue name*/
int singlethread;
int freezeable; /* Freeze threads during suspend */
int rt;
};


工作结构:

struct work_struct {
atomic_long_t data;
struct list_head entry;
work_func_t func;
#ifdef CONFIG_LOCKDEP
struct lockdep_map lockdep_map;
#endif
};


操作流程:

1)创建工作队列;

create_workqueue(name)

name:工作队列名

2)创建工作;

INIT_WORK(_work, _func)

_work:工作

_func:工作处理函数

3)提交工作;

static inline bool queue_work(struct workqueue_struct *wq,
     struct work_struct *work)

wq:工作队列

work:工作

实际上,很少有机会需要我们自己创建工作队列,内核代码中有一个默认的工作队列keventd_wq供我们使用。我们可已使用schedule_work()代替queue_work()向这个默认的工作队列中添加工作,定义如下:

static inline bool schedule_work(struct work_struct *work)

例:

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

struct work_struct work1;
struct work_struct work2;
struct work_struct work3;

void
work_func1(struct work_struct *work)
{
int i;
for(i = 0; i<10; i++) {
printk(KERN_INFO "This is the work1:%d\n", i);
ssleep(1);
}
}

void
work_func2(struct work_struct *work)
{
int i;
for(i = 0; i<10; i++) {
printk(KERN_INFO "This is the work2:%d\n", i);
ssleep(1);
}
}

void
work_func3(struct work_struct *work)
{
int i;
for(i = 0; i<10; i++) {
printk(KERN_INFO "This is the work3:%d\n", i);
ssleep(1);
}
}

static __init int hello_init(void)
{
INIT_WORK(&work1, work_func1);
INIT_WORK(&work2, work_func2);
INIT_WORK(&work3, work_func3);
schedule_work(&work1);
schedule_work(&work2);
schedule_work(&work3);

printk(KERN_ALERT "helloworld!\n");
return 0;
}

static __exit void hello_exit(void)
{
printk(KERN_ALERT "helloworld exit!\n");
}

module_init(hello_init);
module_exit(hello_exit);

MODULE_LICENSE("GPL");
MODULE_AUTHOR("Stone");
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息