Linux work queue and linux queue

Source: Internet
Author: User

Linux work queue and linux queue

Reproduced http://bgutech.blog.163.com/blog/static/18261124320116181119889/

1. What is workqueue?
The Workqueue mechanism in Linux aims to simplify the creation of kernel threads. You can create a kernel thread by calling the workqueue interface. In addition, the number of threads can be created based on the number of CPUs of the current system, so that the transaction processed by the thread can be parallel. Workqueue is a simple and effective mechanism in the kernel. It obviously simplifies the creation of the kernel daemon and facilitates User Programming.

Workqueue is another form of pushing and executing jobs. the work queue can push the work to a kernel thread for execution, that is, the lower half can be executed in the process context. The most important thing is that the work queue can be rescheduled or even sleep.

2. Data Structure
We call the pushed task work, and describe its data structure as work_struct:

 

  1. Struct work_struct {
  2. Atomic_long_t data;/* parameters of the working processing function func */
  3. # Define WORK_STRUCT_PENDING 0/* T if work item pending execution */
  4. # Define WORK_STRUCT_STATIC 1/* static initializer (debugobjects )*/
  5. # Define WORK_STRUCT_FLAG_MASK (3UL)
  6. # Define WORK_STRUCT_WQ_DATA_MASK (~ WORK_STRUCT_FLAG_MASK)
  7. Struct list_head entry;/* connection pointer */
  8. Work_func_t func;/* Work handler */
  9. # Ifdef CONFIG_LOCKDEP
  10. Struct lockdep_map;
  11. # Endif
  12. };

 

These jobs are organized into workqueue in the queue structure, and the data structure is workqueue_struct:

[Cpp]View plain copy
  1. Struct workqueue_struct {
  2. Struct cpu_workqueue_struct * cpu_wq;
  3. Struct list_head list;
  4. Const char * name;/* workqueue name */
  5. Int singlethread;/* Is it single thread-single thread we prefer the first CPU-0 to use the default worker thread event */
  6. Int freezeable;/* Freeze threads during suspend */
  7. Int rt;
  8. };


For multithreading, the structure of cpu_workqueue_struct created by Linux based on the number of CPUs in the current system is:

[Cpp]View plain copy
  1. Truct cpu_workqueue_struct {
  2. Spinlock_t lock;/* because the worker thread needs to frequently process the work connected to it, it needs to be shackled for protection */
  3. Struct list_head worklist;
  4. Wait_queue_head_t more_work;
  5. Struct work_struct * current_work;/* Current work */
  6. Struct workqueue_struct * wq;/* workqueue */
  7. Struct task_struct * thread;/* task context */
  8. }____ Cacheline_aligned;

This structure mainly maintains a task queue and a waiting queue for Kernel threads to sleep. It also maintains a task context, that is, task_struct.
The relationship between the three is as follows:

 

3. Create a job
3.1 create a Job queue
A. create_singlethread_workqueue (name)
Shows the implementation mechanism of this function. The function returns a pointer variable of the type struct workqueue_struct. The memory address pointed to by this pointer variable is dynamically generated by calling kzarloc within the function. Therefore, when the driver no longer uses the work queue, it calls:

Void destroy_workqueue (struct workqueue_struct * wq) to release the memory address.

 

In the figure, cwq is a per-CPU address space. For create_singlethread_workqueue, the kernel is only responsible for creating one worker_thread kernel process for multiple CPU Systems. After the kernel process is created, the wait node in the figure is defined first, and then the worklist in cwq is checked in a loop body. If the queue is empty, then the wait node will be added to the more_work in cwq, and then sleep in the waiting queue.

The Driver calls queue_work (struct workqueue_struct * wq, struct work_struct * work) to add a work node to wq. Work is added to the linked list pointed to by cwq-> worklist in sequence. Queue_work adds a work node to cwq-> worklist and calls wake_up to wake up the worker_thread process sleeping on cwq-> more_work. Wake_up first calls the autoremove_wake_function function on the wait node, and then removes the wait node from cwq-> more_work.

Worker_thread is scheduled again and starts to process all work nodes in the cwq-> worklist... after all the work nodes are processed, worker_thread adds the wait node to cwq-> more_work again, and then sleep in the waiting queue again until the Driver calls queue_work...

B. create_workqueue

 

 

 

 

Compared with create_singlethread_workqueue, create_workqueue also allocates a wq working queue, but the difference is that for multiple CPU Systems, a per-CPU cwq structure is created for each CPU, A new worker_thread process is generated for each cwq. However, when you use queue_work to submit a work node to cwq, which CPU calls this function adds a work node to the worklist of the cwq corresponding to the CPU.

C. Summary
When you call the workqueue initialization interface create_workqueue or create_singlethread_workqueue to initialize the workqueue queue, the kernel begins to assign a workqueue object to the user and link it to a global workqueue queue. Linux then allocates the cpu_workqueue_struct object with the same number of CPUs for the workqueue object based on the current CPU condition. Each cpu_workqueue_struct object will have a task queue. Next, Linux assigns a kernel thread for each cpu_workqueue_struct object, that is, the kernel daemon, to process tasks in each queue. At this point, the user calls the initialization interface to initialize the workqueue and returns the pointer of the workqueue.

After the workqueue Initialization is complete, the Context Environment for running the task is built, but there are no executable tasks, so you need to define a specific work_struct object. Then, add work_struct to the task queue. Linux will wake up daemon to process the task.

The workqueue kernel implementation principles described above can be described as follows:

 

 

 

3.2 Create a job
To use a work queue, you must first create jobs that need to be pushed back. You can use DECLARE_WORK to statically create the structure during compilation:
DECLARE_WORK (name, void (* func) (void *), void * data );
In this way, a work_struct structure named name, func for the function to be executed, and data is created statically.
You can also create a job by using a pointer at runtime:
INIT_WORK (structwork_struct * work, woid (* func) (void *), void * data );

4. Scheduling
A. schedule_work

In most cases, you do not need to create a work queue by yourself. Instead, you only need to define the work and mount the work structure to the predefined event work queue of the kernel for scheduling, in the kernel/workqueue. c defines a static global work queue static struct workqueue_struct * keventd_wq. The default worker thread is events/n. Here n is the processor number, and each processor corresponds to one thread. For example, a single-processor system only has a thread such as events/0. The dual-processor system has one more events/1 thread.
The scheduling work structure adds the work structure to the global event work queue keventd_wq and calls the queue_work general module. The keventd_wq interface is blocked. You do not need to know this parameter, which is equivalent to using the default parameter. Keventd_wq is maintained, created, and destroyed by the kernel. In this way, the work will be scheduled immediately. Once the worker thread on the processor is awakened, It will be executed.

B. schedule_delayed_work (& work, delay );
Sometimes you don't want the job to be executed immediately, but you want it to be executed after a delay. In this case, timer can also be used for delayed scheduling. After expiration, the default timer callback function is used for job registration. After delay is delayed, the timer wakes up and adds work to the wq of the work queue.

The work queue has no priority and is processed in FIFO mode.

 5. Example

[Cpp]View plain copy
  1. # Include <linux/module. h>
  2. # Include <linux/init. h>
  3. # Include <linux/workqueue. h>
  4. Static struct workqueue_struct * queue = NULL;
  5. Static struct work_struct work;
  6. Staticvoid work_handler (struct work_struct * data)
  7. {
  8. Printk (KERN_ALERT "work handler function. \ n ");
  9. }
  10. Static int _ init test_init (void)
  11. {
  12. Queue = create_singlethread_workqueue ("hello world");/* create a single-threaded working queue */
  13. If (! Queue)
  14. Goto err;
  15. INIT_WORK (& work, work_handler );
  16. Schedule_work (& work );
  17. Return0;
  18. Err:
  19. Return-1;
  20. }
  21. Static void _ exit test_exit (void)
  22. {
  23. Destroy_workqueue (queue );
  24. }
  25. MODULE_LICENSE ("GPL ");
  26. Module_init (test_init );
  27. Module_exit (test_exit );

Serial number


Interface functions


Description


1


Create_workqueue


Creates a workqueue queue and creates a kernel thread for each CPU in the system. Input parameters:


@ Name: name of workqueue


2


Create_singlethread_workqueue


Creates workqueue and only one kernel thread. Input parameters:


@ Name: workqueue name


3


Destroy_workqueue


Release the workqueue queue. Input parameters:


@ Workqueue_struct: pointer of the workqueue queue to be released


4


Schedule_work


Schedule and execute a specific task. The task will be attached to the workqueue -- keventd_wq provided by Linux system. Enter the following parameters:


@ Work_struct: task object pointer


5


Schedule_delayed_work


The function is similar to schedule_work. If a specific task is executed with a certain delay time, enter the following parameters:


@ Work_struct: task object pointer


@ Delay: delay Time


6


Queue_work


Schedule and execute a task in the specified workqueue. Input parameters:


@ Workqueue_struct: Specifies the workqueue pointer.


@ Work_struct: task object pointer


7


Queue_delayed_work


Delayed scheduling executes a task in a specified workqueue. The function is similar to queue_work. The input parameter has a delay parameter.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.