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

Linux中的工作队列(work queue)

2009-11-26 10:00 363 查看
工作队列(work queue)是Linux kernel中将工作推后执行的一种机制。这种机制和BH(bottom half)或Tasklets不同之处在于工作队列是把推后的工作交由一个内核线程去执行,因此工作队列的优势就在于它允许重新调度甚至睡眠。

 

linux 2.6.20以后,工作队列机制和之前的版本有一点不同,在网上找了一点资料,也相应的看了一些code,现在自己总结一下:

原文参考:
http://wiki.365linux.cn/index.php?doc-view-39 http://blog.csdn.net/lanmanck/archive/2009/11/05/4770030.aspx
 

work queue的头文件: /kernel/include/linux/workqueue.h

 

work queue的数据结构:

 

struct work_struct {

    atomic_long_t data;

#define WORK_STRUCT_PENDING 0                  /* T if work item pending execution */

#define WORK_STRUCT_FLAG_MASK                 (3UL)

#define WORK_STRUCT_WQ_DATA_MASK         (~WORK_STRUCT_FLAG_MASK)

    struct list_head entry;

    work_func_t func;

#ifdef CONFIG_LOCKDEP

    struct lockdep_map lockdep_map;

#endif

};

 

其中 work_func_t 的定义如下:

typedef void (*work_func_t)(struct work_struct *work);

 

work queue 主要的 API:

 

INIT_WORK(struct work_struct *work, work_func_t func)

INIT_DELAYED_WORK(struct delayed_work *work, work_func_t func)

 

int schedule_work(struct work_struct *work)

void flush_scheduled_work(void)

 

int schedule_delayed_work(struct delayed_work *work, unsigned long delay)

int cancel_delayed_work(struct delayed_work *work)

 

struct workqueue_struct *create_workqueue(const char *name)

int queue_work(struct workqueue_struct *wq, struct work_struct *work)

int queue_delayed_work(struct workqueue_struct *wq, struct delayed_work *work, unsigned long delay)

void flush_workqueue(struct workqueue_struct *wq)

void destroy_workqueue(struct workqueue_struct *wq)

 

work queue 的使用实例:

struct my_work_t {

    char *name;

    struct work_struct work;                 //作为自己数据结构的成员,然后用container_of获得my_work_t的指针

};

 

void my_func(struct work_struct *work)

{

    struct my_work_t *my_work = container_of
(work, struct my_work_t, work);

    printk(KERN_INFO “Hello world, my name is %s!/n”, my_work->name);

}

 

struct workqueue_struct *my_wq = create_workqueue(“my wq”);      //创建自己的work queue

struct my_work_t my_work;

 

my_work.name = “Jack”;

 

INIT_WORK(&(my_work.work), my_func);                //初始化自己的work queue

queue_work(my_wq, &(my_work.work));

 

destroy_workqueue(my_wq);                     //销毁自己的work queue
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息