工作队列的实现

        工作队列(work queue)是另外一种将工作推后执行的形式。工作队列可以把工作推后,交由一个内核线程去执行----这个下半部分总是会在进程上下文执行。这样,通过工作队列执行的代码能占尽进程上下文的所有优势。最重要的就是工作队列允许重新调度甚至是睡眠。

       如果推后执行的任务需要睡眠,那么就选择工作队列;如果推后执行的任务不需要睡眠,那么就选择软中断或tasklet。实际上,工作队列通常可以用内核线程替换。但那是由于内核开发者们非常反对创建新的内核线程,所以推荐使用工作队列。如果需要用一个可以重新调度的实体来执行你的下半部处理,应该使用工作对列。它是唯一能在进程上下文运行的下半部实现的机制,也只有它才可以睡眠。这意味着在你需要获得大量的内存时、在你需要获取信号量时,在你需要执行阻塞式的I/O操作时,它都会非常有用。如果你不需要用一个内核线程来推后执行工作,那么就考虑使用tasklet吧。

 

下面介绍工作队列的实现

 

       工作队列子系统是一个用于创建内核线程的接口,通过它创建的进程负责执行由内核其他部分排到队列的任务。它创建的这些内核线程被称作工作者线程(worker thread)。工作队列可以让你的驱动程序创建一个专门的工作者线程来处理需要推后的工作。不过,工作对垒子系统提供了一个默认的工作者线程来处理这些工作。因此,工作队列最基本的表现形式就转变成了一个把需要推后执行的任务交给特定的通用线程这样一种接口。

       默认的工作者线程叫做events/n,这里n是处理器的编号,每个处理器对应一个线程。默认的工作者线程会从多个地方得到被推后的工作。许多内核驱动程序都把它们的下半部交给默认的工作者线程去做。除非一个驱动程序或者子系统必须建立一个属于它自己的内核线程,否则最好使用默认线程。

      如果要执行大量的处理操作的话,创建属于自己的工作者线程是个很好的选择。处理器密集型和性能要求严格的任务会因为拥有自己的工作者线程而获得好处。此时,这样做有助于减轻默认线程的负担,避免工作队列中其他需要完成的工作处于饥饿状态。

 

1.表示线程的数据结构

  1. 在<kernel/workqueue.c>中
  2. /*
  3.  * The externally visible workqueue abstraction is an array of
  4.  * per-CPU workqueues:
  5.  */
  6. struct workqueue_struct {
  7.     struct cpu_workqueue_struct *cpu_wq;
  8.     const char *name;
  9.     struct list_head list;  /* Empty if single thread */
  10. };

        该结构内是一个由cpu_workqueue_struct结构组成的数组,数组的每一项对应系统中的一个处理器。由于系统中每个处理器对应一个工作者线程。所以对于给定的某台计算机来说,就是每个处理器,每个工作者线程对应一个这样的cpu_workqueue_struct结构体。

 

  1. 在<kernel/workqueue.c>中
  2. /*
  3.  * The per-CPU workqueue (if single thread, we always use the first
  4.  * possible cpu).
  5.  *
  6.  * The sequence counters are for flush_scheduled_work().  It wants to wait
  7.  * until all currently-scheduled works are completed, but it doesn't
  8.  * want to be livelocked by new, incoming ones.  So it waits until
  9.  * remove_sequence is >= the insert_sequence which pertained when
  10.  * flush_scheduled_work() was called.
  11.  */
  12. struct cpu_workqueue_struct {
  13.     spinlock_t lock;
  14.     long remove_sequence;   /* Least-recently added (next to run) */
  15.     long insert_sequence;   /* Next to add */
  16.     struct list_head worklist;
  17.     wait_queue_head_t more_work;
  18.     wait_queue_head_t work_done;
  19.     struct workqueue_struct *wq;      /* 有关联的workqueue_struct结构*/
  20.   struct task_struct *thread;         /* 有关联的线程 */
  21.     int run_depth;      /* Detect run_workqueue() recursion depth */
  22.     int freezeable;     /* Freeze the thread during suspend */
  23. } ____cacheline_aligned;

       注意,每个工作者线程类型关联一个自己的workqueue_struct。在结构里面,给每个线程分配一个cpu_workqueue_struct ,因而也就是给每个处理器分配一个,因为每个处理器都有一个该类型的工作者线程。

 

  2.表示工作的数据结构

        所有的工作者线程都是用普通的内核线程实现的,它们都要执行worker_thread()函数。在它初始化完之后,这个函数执行一个死循环并开始休眠。当有操作被插入到队列里的时候,线程就会被唤醒,以便执行这些操作。当没有剩余的操作时,它又会继续休眠。

 

  1. 在<linux/workqueue.c>中
  2. static int worker_thread(void *__cwq)
  3. {
  4.     struct cpu_workqueue_struct *cwq = __cwq;
  5.     DECLARE_WAITQUEUE(wait, current);
  6.     struct k_sigaction sa;
  7.     sigset_t blocked;
  8.     if (!cwq->freezeable)
  9.         current->flags |= PF_NOFREEZE;
  10.     set_user_nice(current, -5);
  11.     /* Block and flush all signals */
  12.     sigfillset(&blocked);
  13.     sigprocmask(SIG_BLOCK, &blocked, NULL);
  14.     flush_signals(current);
  15.     /*
  16.      * We inherited MPOL_INTERLEAVE from the booting kernel.
  17.      * Set MPOL_DEFAULT to insure node local allocations.
  18.      */
  19.     numa_default_policy();
  20.     /* SIG_IGN makes children autoreap: see do_notify_parent(). */
  21.     sa.sa.sa_handler = SIG_IGN;
  22.     sa.sa.sa_flags = 0;
  23.     siginitset(&sa.sa.sa_mask, sigmask(SIGCHLD));
  24.     do_sigaction(SIGCHLD, &sa, (struct k_sigaction *)0);
  25.     set_current_state(TASK_INTERRUPTIBLE);   /* 线程将自己设置为休眠状态*/
  26.     while (!kthread_should_stop()) {
  27.         if (cwq->freezeable)
  28.             try_to_freeze();
  29.         add_wait_queue(&cwq->more_work, &wait);    /* 线程将自己加入等待队列上*/
  30.         if (list_empty(&cwq->worklist))  /*如果工作链表是空的,线程调用schedule()函数,进入睡眠状态*/
  31.             schedule();
  32.         else/* 如果链表中有对象,线程不会睡眠。它将自己设置成TASKLET_RUNNING脱离等待队列*/
  33.             __set_current_state(TASK_RUNNING);
  34.         remove_wait_queue(&cwq->more_work, &wait);
  35.         if (!list_empty(&cwq->worklist))/* 如果链表非空,调用run_workqueue()函数执行被推后的工作*/
  36.             run_workqueue(cwq);
  37.         set_current_state(TASK_INTERRUPTIBLE);
  38.     }
  39.     __set_current_state(TASK_RUNNING);
  40.     return 0;
  41. }
  42. 在<kernel/Kthread.c>中
  43. /**
  44.  * kthread_should_stop - should this kthread return now?
  45.  *
  46.  * When someone calls kthread_stop() on your kthread, it will be woken
  47.  * and this will return true.  You should then return, and your return
  48.  * value will be passed through to kthread_stop().
  49.  */
  50. int kthread_should_stop(void)
  51. {
  52.     return (kthread_stop_info.k == current);
  53. }
  54. 在<kernel/Workqueue.c>中
  55. static void run_workqueue(struct cpu_workqueue_struct *cwq)
  56. {
  57.     unsigned long flags;
  58.     /*
  59.      * Keep taking off work from the queue until
  60.      * done.
  61.      */
  62.     spin_lock_irqsave(&cwq->lock, flags);
  63.     cwq->run_depth++;
  64.     if (cwq->run_depth > 3) {
  65.         /* morton gets to eat his hat */
  66.         printk("%s: recursion depth exceeded: %d/n",
  67.             __FUNCTION__, cwq->run_depth);
  68.         dump_stack();
  69.     }
  70.     while (!list_empty(&cwq->worklist)) {
  71.        /*获得执行函数和参数*/
  72.         struct work_struct *work = list_entry(cwq->worklist.next,
  73.                         struct work_struct, entry);
  74.         work_func_t f = work->func;
  75.         list_del_init(cwq->worklist.next);
  76.         spin_unlock_irqrestore(&cwq->lock, flags);
  77.         BUG_ON(get_wq_data(work) != cwq);
  78.         if (!test_bit(WORK_STRUCT_NOAUTOREL, work_data_bits(work)))
  79.             work_release(work);
  80.         f(work);  /*执行函数*/
  81.         if (unlikely(in_atomic() || lockdep_depth(current) > 0)) {
  82.             printk(KERN_ERR "BUG: workqueue leaked lock or atomic: "
  83.                     "%s/0x%08x/%d/n",
  84.                     current->comm, preempt_count(),
  85.                         current->pid);
  86.             printk(KERN_ERR "    last function: ");
  87.             print_symbol("%s/n", (unsigned long)f);
  88.             debug_show_held_locks(current);
  89.             dump_stack();
  90.         }
  91.         spin_lock_irqsave(&cwq->lock, flags);
  92.         cwq->remove_sequence++;
  93.         wake_up(&cwq->work_done);
  94.     }
  95.     cwq->run_depth--;
  96.     spin_unlock_irqrestore(&cwq->lock, flags);
  97. }
  1. 在<List.h(include/linux)>中
  2. /**
  3.  * list_del_init - deletes entry from list and reinitialize it.
  4.  * @entry: the element to delete from the list.
  5.  */
  6. static inline void list_del_init(struct list_head *entry)
  7. {
  8.     __list_del(entry->prev, entry->next);
  9.     INIT_LIST_HEAD(entry);
  10. }
  11. /*
  12.  * Delete a list entry by making the prev/next entries
  13.  * point to each other.
  14.  *
  15.  * This is only for internal list manipulation where we know
  16.  * the prev/next entries already!
  17.  */
  18. static inline void __list_del(struct list_head * prev, struct list_head * next)
  19. {
  20.     next->prev = prev;
  21.     prev->next = next;
  22. }
  23. static inline void INIT_LIST_HEAD(struct list_head *list)
  24. {
  25.     list->next = list;
  26.     list->prev = list;
  27. }

   

工作用work_struct结构体表示:

 

  1. 在<include/linux/Workqueue.h>
  2. typedef void (*work_func_t)(struct work_struct *work);
  3. /*
  4.  * The first word is the work queue pointer and the flags rolled into
  5.  * one
  6.  */
  7. #define work_data_bits(work) ((unsigned long *)(&(work)->data)) 
  8. struct work_struct {
  9.     atomic_long_t data;
  10. #define WORK_STRUCT_PENDING 0       /* T if work item pending execution */ 
  11. #define WORK_STRUCT_NOAUTOREL 1     /* F if work item automatically released on exec */ 
  12. #define WORK_STRUCT_FLAG_MASK (3UL) 
  13. #define WORK_STRUCT_WQ_DATA_MASK (~WORK_STRUCT_FLAG_MASK) 
  14.     struct list_head entry;
  15.     work_func_t func;
  16. };

        这些结构体被连接成链表,在每个处理器上的每种类型的队列都对应这样一个链表。比如,每个处理器上用于执行被推后的工作的那个通用线程就有一个这样的链表。当一个工作者线程被唤醒时,它会执行它的链表上的所有工作。工作被执行完毕,它就将相应的work_struct对象从链表上移去。当链表上不再有对象的时候,它就会继续休眠。

 

3.数据结构间的关系

 

 

 

    位于最高一层的是工作者线程。系统允许有多种类型的工作者线程存在。对于指定的一个类型,系统的每个CPU上都有一个该类的工作者线程。内核中有些不封可以根据需要来创建工作者线程。而在默认情况下内核只有events这一种类型的工作者线程。每个工作者线程都由一个cpu_workqueue_struct结构体表示。而workqueue_struct结构体则表示给定类型的所有工作者线程。

    工作处于最低一层。你的驱动程序创建这些需要推后执行的工作(可以理解成用“工作”这种接口封装我们实际需要推后的工作,以便后续的工作者线程处理)。它们用work_struct结构来表示。这个结构体中最重要的部分是一个指针,它指向一个函数,而正是该函数负责处理需要推后执行的具体任务。工作会被提交给某个具体的工作者线程。然后这个工作者线程会被唤醒并执行这些安排好的给偶内置。

      大部分驱动程序都使用的是现存的默认工作者线程。在有些要求更严格的情况下,驱动程序需要自己的工作者线程。

 

呵呵,终于又帖完了:P

下午弄了很久,虽然点了“发表文章”但是还是失败了,希望这次能成功!!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值