Chinaunix首页 | 论坛 | 博客
  • 博客访问: 400007
  • 博文数量: 73
  • 博客积分: 3120
  • 博客等级: 中校
  • 技术积分: 785
  • 用 户 组: 普通用户
  • 注册时间: 2010-10-20 12:26
文章分类

全部博文(73)

文章存档

2013年(4)

2012年(10)

2011年(32)

2010年(27)

分类: LINUX

2010-12-04 15:26:07

1.       头文件

#include    //wake_up_process()

#include //kthread_create()kthread_run()

#include //IS_ERR()PTR_ERR()

2.       实现

2.1创建线程

在模块初始化时,可以进行线程的创建。使用下面的函数和宏定义:

struct task_struct *kthread_create(int (*threadfn)(void *data),

                            void *data,

                            const char namefmt[], ...);

      //该函数创建,但并不启动线程,创建完后要通过wake_up_process启动。

#define kthread_run(threadfn, data, namefmt, ...)                     \

({                                                            \

    struct task_struct *__k                                        \

           = kthread_create(threadfn, data, namefmt, ## __VA_ARGS__); \

    if (!IS_ERR(__k))                                        \

           wake_up_process(__k);                                \

    __k;                                                     \

})

//创建并运行线程


2.2线程函数

在线程函数为一个无限循环,并需要在循环里检查停止条件:

int threadfunc(void *data){

       

        while(1){


               if(kthread_should_stop()) break;

               if(){

                   //条件为真,开始处理相关任务

               }

               else{

                      //否则让出CPU,并在指定的时间内重新被调度

                      schedule_timeout(HZ);

                      //此处不能用mdelay及udelay,因为这两个函数属于循环等待,不会让出CPU

               }

        }

       

        return 0;

}

2.3结束线程

int kthread_stop(struct task_struct *k);

        该函数发送停止信号给线程,线程函数主循环中通过kthread_should_stop()检查是否有停止信号,若有停止信号,则退出线程。

3性能测试

可以使用top命令来查看线程(包括内核线程)的CPU利用率。命令如下:

       top –p 线程号

可以使用下面命令来查找线程号:

       ps aux|grep 线程名

       注:线程名由kthread_create函数的第三个参数指定。

4.参考测试代码:
#include 
#include 
#ifndef SLEEP_MILLI_SEC
#define SLEEP_MILLI_SEC(nMilliSec)\
do { \
long timeout = (nMilliSec) * HZ / 1000; \
while(timeout > 0) \
{ \
timeout = schedule_timeout(timeout); \
} \
}while(0);
#endif
static struct task_struct * MyThread = NULL;
static int MyPrintk(void *data)
{
  char *mydata = kmalloc(strlen(data)+1,GFP_KERNEL);
  memset(mydata,'\0',strlen(data)+1);
  strncpy(mydata,data,strlen(data));
  while(!kthread_should_stop())//检查停止信号
  {
    SLEEP_MILLI_SEC(1000);//睡眠等待
    printk("%s\n",mydata);
  }
  kfree(mydata);
  return 0;
}
static int __init init_kthread(void)
{
  MyThread = kthread_run(MyPrintk,"hello world","mythread");
  return 0;
}
static void __exit exit_kthread(void)
{
  if(MyThread)
  {
    printk("stop MyThread\n");
    kthread_stop(MyThread);//发送停止信号
  }
}
module_init(init_kthread);
module_exit(exit_kthread);
这个内核线程的作用就是每隔一秒打印一个“hello world”

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

chinaunix网友2010-12-07 10:13:24

很好的, 收藏了 推荐一个博客,提供很多免费软件编程电子书下载: http://free-ebooks.appspot.com