Linux内核多线程(三)

来源:互联网 发布:uc矩阵表主要作用 编辑:程序博客网 时间:2024/05/05 20:17

接上 一篇文章 ,这里介绍另一种线程间通信的方式:completion机制。Completion机制是线程间通信的一种轻量级机制:允许一个线程告诉另一个线程工作已经完成。为使用 completion, 需要包含头文件 <linux/completion.h>。

可以通过以下方式来创建一个 completion :

DECLARE_COMPLETION(my_completion);

或者, 动态创建和初始化:

struct completion my_completion;

init_completion(&my_completion);

等待 completion 是一个简单事来调用: void wait_for_completion(struct completion *c); 

注意:这个函数进行一个不可打断的等待. 如果你的代码调用 wait_for_completion 并且

没有人完成这个任务, 结果会是一个不可杀死的进程。

completion 事件可能通过调用下列之一来发出:

void complete(struct completion *c);

void complete_all(struct completion *c);

如果多于一个线程在等待同一个 completion 事件, 这 2 个函数做法不同. complete 只

唤醒一个等待的线程, 而 complete_all 允许它们所有都继续。

下面来看使用completion机制的实现代码:

复制代码
#include <linux/init.h>   #include <linux/module.h>   #include <linux/kthread.h>   #include <linux/wait.h>#include <linux/completion.h>  MODULE_LICENSE("Dual BSD/GPL");    static struct completion  comp;  static struct task_struct * _tsk;  static struct task_struct * _tsk1;static int tc = 0; static int thread_function(void *data)  {      do {                printk(KERN_INFO "IN thread_function thread_function: %d times \n", tc);                          wait_for_completion(&comp);                   //tc = 0;  ///在哪里都行                                      printk(KERN_INFO "has been woke up !\n");    }while(!kthread_should_stop());      return tc;  }    static int thread_function_1(void *data)  {      do {                printk(KERN_INFO "IN thread_function_1 thread_function: %d times\n", ++tc);                            if(tc == 10)                   {                            complete(&comp);                            tc = 0;                   }                   msleep_interruptible(1000);                      }while(!kthread_should_stop());      return tc;  }    static int hello_init(void)  {      printk(KERN_INFO "Hello, world!\n");      init_completion(&comp);    _tsk = kthread_run(thread_function, NULL, "mythread");     if (IS_ERR(_tsk)) {          printk(KERN_INFO "first create kthread failed!\n");      }      else {          printk(KERN_INFO "first create ktrhead ok!\n");      }            _tsk1 = kthread_run(thread_function_1,NULL, "mythread2");    if (IS_ERR(_tsk1)) {          printk(KERN_INFO "second create kthread failed!\n");      }      else {          printk(KERN_INFO "second create ktrhead ok!\n");      }      return 0;  }    static void hello_exit(void)  {      printk(KERN_INFO "Hello, exit!\n");      if (!IS_ERR(_tsk)){          int ret = kthread_stop(_tsk);          printk(KERN_INFO "First thread function has stopped ,return %d\n", ret);      }      if(!IS_ERR(_tsk1))         {                   int ret = kthread_stop(_tsk1);                   printk(KERN_INFO "Second thread function_1 has stopped ,return %d\n",ret);         }}   module_init(hello_init);  module_exit(hello_exit);  
复制代码

 

运行结果:

0 0
原创粉丝点击