当前位置:   article > 正文

了解函数queue_delayed_work()_queue_delayed_work用法

queue_delayed_work用法
  1. /**********************************************
  2.  * Author: lewiyon@hotmail.com
  3.  * File name: delay_wq.c
  4.  * Description: learn the function queue_delayed_work()
  5.  * Date: 2011-12-24
  6.  *********************************************/
  7. #include <linux/kernel.h>
  8. #include <linux/module.h>
  9. #include <linux/proc_fs.h>
  10. #include <linux/workqueue.h>
  11. #include <linux/sched.h>
  12. #include <linux/init.h>
  13. #include <linux/interrupt.h>
  14. #include <linux/delay.h>
  15. struct workqueue_struct *test_wq;
  16. struct delayed_work test_dwq;
  17. void delay_func(struct work_struct *work);
  18. void delay_func(struct work_struct *work)
  19. {
  20.     int i;
  21.     printk(KERN_INFO "My name is delay_func!\n");
  22.     for (i = 0; i < 3; i++) {
  23.         printk(KERN_ERR "delay_fun:i=%d\n", i);
  24.         msleep(1000);
  25.     }
  26. }
  27. static int __init example_init(void)
  28. {
  29.     int i;
  30.     int ret;
  31.     test_wq = create_workqueue("test_wq");
  32.     if (!test_wq) {
  33.         printk(KERN_ERR "No memory for workqueue\n");
  34.         return 1;   
  35.     }
  36.     printk(KERN_INFO "Create Workqueue successful!\n");
  37.     INIT_DELAYED_WORK(&test_dwq, delay_func);
  38.     
  39.     ret = queue_delayed_work(test_wq, &test_dwq, 5000);
  40.     printk(KERN_INFO "first ret=%d!\n", ret);
  41.     
  42.     for (i = 0; i < 3; i++) { 
  43.         printk(KERN_INFO "Example:ret= %d,i=%d\n", ret, i);
  44.         msleep(100);
  45.     }
  46.     ret = queue_delayed_work(test_wq, &test_dwq, 0);
  47.     printk(KERN_INFO "second ret=%d!\n", ret);
  48. return 0;
  49. }
  50. static void __exit example_exit(void)
  51. {
  52.     int ret;
  53.     ret = cancel_delayed_work(&test_dwq);
  54.     flush_workqueue(test_wq);
  55.     destroy_workqueue(test_wq);
  56.     printk(KERN_INFO "Goodbay! ret=%d\n", ret);
  57. }
  58. module_init(example_init);
  59. module_exit(example_exit);
  60. MODULE_LICENSE("GPL");
  61. MODULE_AUTHOR("lewiyon <lewiyon@hotmail.com>");

运行结果:

  1. Dec 24 20:50:40 RedHat kernel: Create Workqueue successful!
  2. Dec 24 20:50:40 RedHat kernel: first ret=1!
  3. Dec 24 20:50:40 RedHat kernel: Example:ret= 1,i=0
  4. Dec 24 20:50:41 RedHat kernel: Example:ret= 1,i=1
  5. Dec 24 20:50:41 RedHat kernel: Example:ret= 1,i=2
  6. Dec 24 20:50:41 RedHat kernel: second ret=0!
  7. Dec 24 20:50:43 RedHat kernel: Goodbay! ret=1
说明将任务添加到工作队列后,如果工作队列还在执行该任务,则queue_delayed_work()返回1,否则返回0,如上实例所述;

主线程delay_wq将任务添加到工作队列后,使得工作队列在延迟delay后执行函数delay_func(),而delay_wq线程继续执行;

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/88532
推荐阅读
相关标签
  

闽ICP备14008679号