Chinaunix首页 | 论坛 | 博客
  • 博客访问: 3310383
  • 博文数量: 258
  • 博客积分: 9440
  • 博客等级: 少将
  • 技术积分: 6998
  • 用 户 组: 普通用户
  • 注册时间: 2009-05-03 10:28
个人简介

-- linux爱好者,业余时间热衷于分析linux内核源码 -- 目前主要研究云计算和虚拟化相关的技术,主要包括libvirt/qemu,openstack,opennebula架构和源码分析。 -- 第五届云计算大会演讲嘉宾 微博:@Marshal-Liu

文章分类

全部博文(258)

文章存档

2016年(1)

2015年(4)

2014年(16)

2013年(22)

2012年(41)

2011年(59)

2010年(40)

2009年(75)

分类: LINUX

2011-03-28 17:07:53

Linux系统提供了一种比信号量更好的同步机制,即completion,它用于一个执行单元等待另一个执行单元执行完某事。Linux系统中与completion相关的操作主要有以下4种:
    (1) 定义completion

  1. struct completion my_completion;
    (2) 初始化completion

  1. init_completion(&my_completion);
        对my_completion的定义和初始化可以通过如下快捷方式实现
        DECLEARE_COMPLETION(my_completion);
    (3) 等待completion

  1. void wait_for_completion(struct completion *c);
    (4) 唤醒completion
  1. void complete(struct completion *c);
  2. void complete_all(struct completion *c);
        前者只唤醒一个等待的执行单元,后者唤醒所有等待同一completion的执行单元。


     执行单元A                                                    执行单元B
    struct completion com;
    init_completion(&com);
                                                          wake up
    wait_for_completion(&com); <----------- complete(&com);

  1. kernel_thread.c
  2. ---------------------------------------
  3. #include <linux/kernel.h>
  4. #include <linux/module.h>
  5. #include <linux/init.h>
  6. #include <linux/param.h>
  7. #include <linux/jiffies.h>
  8. #include <asm/system.h>
  9. #include <asm/processor.h>
  10. #include <asm/signal.h>
  11. #include <linux/completion.h> // for DECLARE_COMPLETION()
  12. #include <linux/sched.h> // for daemonize() and set_current_state()
  13. #include <linux/delay.h> // mdelay()

  14. static pid_t thread_id;
  15. static DECLARE_COMPLETION(my_completion);

  16. int my_fuction(void *arg)
  17. {
  18.     printk("<1> in %s()\n", __FUNCTION__);
  19.     daemonize("demo-thread");
  20.     allow_signal(SIGKILL);
  21.     mdelay(2000);
  22.     printk("<1> my_function complete()\n");
  23.     complete(&my_completion); // wake up wait_for_completion

  24.     while (!signal_pending(current)) { /* 等待处理信号,没有信号将进入循环体 */
  25.         printk("<1> jiffies is %lu\n", jiffies);
  26.         set_current_state(TASK_INTERRUPTIBLE);
  27.         schedule_timeout(HZ * 5);
  28.     }

  29.     return 0;
  30. }

  31. static int __init init(void)
  32. {
  33.     thread_id = kernel_thread(my_fuction, NULL, CLONE_FS | CLONE_FILES);
  34.     printk("<1> init wait_for_completion()\n");
  35.     wait_for_completion(&my_completion);
  36.     return 0;
  37. }

  38. static void __exit finish(void)
  39. {
  40.     kill_proc(thread_id, SIGKILL, 1);/* 结束内核线程、杀死内核线程 */
  41.     printk("<1> Goodbye\n");
  42. }

  43. module_init(init);
  44. module_exit(finish);
  45. MODULE_LICENSE("GPL");

阅读(2636) | 评论(0) | 转发(2) |
给主人留下些什么吧!~~