Linux中的工作队列(work queue)

工作队列(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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值