内核线程 && completion使用方法

转自:http://blog.csdn.net/skywalkzf/article/details/4409034

Linux系统提供了一种比信号量更好的同步机制,即completion,它用于一个执行单元等待另一个执行单元执行完某事。Linux系统中与completion相关的操作主要有以下4种:
    (1) 定义completion
        struct completion my_completion;
    (2) 初始化completion
        init_completion(&my_completion);
        对my_completion的定义和初始化可以通过如下快捷方式实现
        DECLEARE_COMPLETION(my_completion);
    (3) 等待completion
        void wait_for_completion(struct completion *c);
    (4) 唤醒completion
        void complete(struct completion *c);
        void complete_all(struct completion *c);
        前者只唤醒一个等待的执行单元,后者唤醒所有等待同一completion的执行单元。


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

 

kernel_thread.c

  1. ---------------------------------------  
  2. #include <linux/kernel.h>  
  3. #include <linux/module.h>  
  4. #include <linux/init.h>  
  5. #include <linux/param.h>  
  6. #include <linux/jiffies.h>  
  7. #include <asm/system.h>  
  8. #include <asm/processor.h>  
  9. #include <asm/signal.h>  
  10. #include <linux/completion.h>       // for DECLARE_COMPLETION()  
  11. #include <linux/sched.h>            // for daemonize() and set_current_state()   
  12. #include <linux/delay.h>            // mdelay()  
  13.   
  14. static pid_t thread_id;  
  15. static DECLARE_COMPLETION(my_completion);  
  16.   
  17. int my_fuction(void *arg)  
  18. {  
  19.     printk("<1> in %s()/n", __FUNCTION__);  
  20.     daemonize("demo-thread");  
  21.     allow_signal(SIGKILL);  
  22.     mdelay(2000);  
  23.     printk("<1> my_function complete()/n");  
  24.     complete(&my_completion); // wake up wait_for_completion  
  25.   
  26.     while (!signal_pending(current)) {       // no signal  
  27.         printk("<1> jiffies is %lu/n", jiffies);  
  28.         set_current_state(TASK_INTERRUPTIBLE);  
  29.         schedule_timeout(HZ * 5);      
  30.     }  
  31.   
  32.     return 0;  
  33. }  
  34.   
  35. static int __init init(void)  
  36. {  
  37.     thread_id = kernel_thread(my_fuction, NULL, CLONE_FS | CLONE_FILES);  
  38.     printk("<1> init wait_for_completion()/n");  
  39.     wait_for_completion(&my_completion);  
  40.     return 0;  
  41. }  
  42.   
  43. static void __exit finish(void)  
  44. {  
  45.     kill_proc(thread_id, SIGKILL, 1);  
  46.     printk("<1> Goodbye/n");  
  47. }  
  48.   
  49. module_init(init);  
  50. module_exit(finish);  
  51. MODULE_LICENSE("GPL");  


Makefile
---------------------------------------
KDIR=/usr/src/kernels/2.6.23.1-42.fc8-i686
obj-m += kernel_thread.o

all:
    make -C $(KDIR) M=`pwd` modules

clean:   
    make -C $(KDIR) M=`pwd` clean

posted @ 2012-11-17 20:41  云翔世界  阅读(200)  评论(0)    收藏  举报