kthread_create与kernel_thread的区别

Kernel threads made easy


从表面上来看,这两个函数非常的类似,但是实现却是相差甚远。
kthread_create是通过work_queue来实现的,kernel_thread是通过do_fork来实现的。

 

kernelthread可以用kernel_thread创建,但是在执行函数里面必须用daemonize释放资源并挂到init下,还需要用completion等待这一过程的完成。


kthread_create是比较正牌的创建函数,这个不必要调用daemonize,用这个创建的kernelthread都挂在了kthread线程下。

 

 

 

 

可以在非内核线程中调用kernel_thread,但这样创建的线程必须在自己调用daemonize(...)来释放资源,成为真正的内核线程。

#include <linux/kernel.h>
#include <linux/module.h>
static int noop(void *dummy)
{
       int i = 0;
       daemonize("mythread");
       while(i++ < 5) {
               printk("current->mm = %p\n",current->mm);
               printk("current->active_mm = %p\n",current->active_mm);
               set_current_state(TASK_INTERRUPTIBLE);
               schedule_timeout(10 * HZ);
       }
       return 0;
}
static int test_init(void)
{
       kernel_thread(noop, NULL, CLONE_KERNEL | SIGCHLD);
       return 0;
}
static void test_exit(void) {}
module_init(test_init);
module_exit(test_exit);

”mythread“就是给这个内核线程取的名字, 可以用ps -A来查看。
schedule()用于进程调度, 可以理解为放弃CPU的使用权.

 

 

 

 

 kthread_create创建线程

1 使用kthread_create创建线程:
    structtask_struct *kthread_create(int (*threadfn)(void*data),
                                            void*data,
                                           const char *namefmt, ...);
这个函数可以像printk一样传入某种格式的线程名
线程创建后,不会马上运行,而是需要将kthread_create()返回的task_struct指针传给wake_up_process(),然后通过此函数运行线程。
2. 当然,还有一个创建并启动线程的函数:kthread_run
   struct task_struct*kthread_run(int (*threadfn)(void *data),
                                   void *data,
                                   const char *namefmt, ...);
3.线程一旦启动起来后,会一直运行,除非该线程主动调用do_exit函数,或者其他的进程调用kthread_stop函数,结束线程的运行。
    intkthread_stop(struct task_struct *thread);
kthread_stop() 通过发送信号给线程。
如果线程函数正在处理一个非常重要的任务,它不会被中断的。当然如果线程函数永远不返回并且不检查信号,它将永远都不会停止。
参考:Kernel threads made easy
--
view plaincopy toclipboardprint?
#include<linux/kthread.h>  
static struct task_struct *_task;  
static struct task_struct *_task2;  
static struct task_struct *_task3;  
static int thread_func(void*data)  
 
       int j,k;  
       int timeout;  
       wait_queue_head_ttimeout_wq;  
       static int i =0;         
       i++;  
       j = 0;  
       k = i;  
       printk("thread_func %d started\n",i);  
       init_waitqueue_head(&timeout_wq);  
       while(!kthread_should_stop())  
        
               interruptible_sleep_on_timeout(&timeout_wq,HZ);  
               printk("[%d]sleeping..%d\n", k,j++);  
        
       return 0;  
 
voidmy_start_thread(void)  
 
          
       //_task = kthread_create(thread_func, NULL,"thread_func2");  
       //wake_up_process(_task);  
       _task = kthread_run(thread_func, NULL,"thread_func2");  
       _task2 = kthread_run(thread_func, NULL,"thread_func2");  
       _task3 = kthread_run(thread_func, NULL,"thread_func2");  
       if (!IS_ERR(_task))  
        
               printk("kthread_createdone\n");  
        
       else 
        
               printk("kthread_createerror\n");  
        
 
void my_end_thread(void)  
 
       int ret = 0;  
       ret =kthread_stop(_task);  
       printk("end thread. ret = %d\n" ,ret);  
       ret =kthread_stop(_task2);  
       printk("end thread. ret = %d\n" ,ret);  
       ret =kthread_stop(_task3);  
       printk("end thread. ret = %d\n" ,ret);  

#include <linux/kthread.h>
static struct task_struct * _task;
static struct task_struct * _task2;
static struct task_struct * _task3;
static int thread_func(void *data)
{
       int j,k;
       int timeout;
       wait_queue_head_t timeout_wq;
       static int i =0;      
       i++;
       j = 0;
       k = i;
       printk("thread_func %d started\n", i);
       init_waitqueue_head(&timeout_wq);
       while(!kthread_should_stop())
       {
               interruptible_sleep_on_timeout(&timeout_wq,HZ);
               printk("[%d]sleeping..%d\n", k, j++);
       }
       return 0;
}
void my_start_thread(void)
{
       
       //_task = kthread_create(thread_func, NULL, "thread_func2");
       //wake_up_process(_task);
       _task = kthread_run(thread_func, NULL, "thread_func2");
       _task2 = kthread_run(thread_func, NULL, "thread_func2");
       _task3 = kthread_run(thread_func, NULL, "thread_func2");
       if (!IS_ERR(_task))
       {
               printk("kthread_create done\n");
       }
       else
       {
               printk("kthread_create error\n");
       }
}
void my_end_thread(void)
{
       int ret = 0;
       ret = kthread_stop(_task);
       printk("end thread. ret = %d\n" , ret);
       ret = kthread_stop(_task2);
       printk("end thread. ret = %d\n" , ret);
       ret = kthread_stop(_task3);
       printk("end thread. ret = %d\n" , ret);
}
在执行kthread_stop的时候,目标线程必须没有退出,否则会Oops。原因很容易理解,当目标线程退出的时候,其对应的task结构也变得无效,kthread_stop引用该无效task结构就会出错。
为了避免这种情况,需要确保线程没有退出,其方法如代码中所示:
thread_func()
{
   // do your work here
   // wait to exit
   while(!thread_could_stop())
   {
          wait();
   }
}
exit_code()
{
    kthread_stop(_task);  //发信号给task,通知其可以退出了
}
这种退出机制很温和,一切尽在thread_func()的掌控之中,线程在退出时可以从容地释放资源,而不是莫名其妙地被人“暗杀”。
kernel_thread 是内核创建线程的函数,供系统调用。
在2.4.0中kernel_thread 的代码:
int kernel_thread(int (*fn)(void *), void * arg, unsigned long flags) 

{ 

   long retval, d0; 

  __asm__ __volatile__(

     “movl %%esp,%%esi\n\t" //  

  "int $0x80\n\t"          

  "cmpl %%esp,%%esi\n\t"  
  "je 1f\n\t"              

  arch/i386/kernel/process.c#L449" id="L449" class="line" name="L449">                 * not matter whether the called function is     

     compiled with                  * -mregparm or not.  */                  

    "movl %4,%�x\n\t" 

  "pushl %�x\n\t" 

  "call *%5\n\t"           

  "movl %3,%0\n\t"         

  "int $0x80\n" 

  "1:\t" 

  :"=&a" (retval), "=&S" (d0) // eax 与变量retval 结合 

  :"0" (__NR_clone), "i" (__NR_exit), //调用的函数有:sys_clone 、sys_exit

  "r" (arg), "r" (fn), 

  "b" (flags | CLONE_VM) 

  : "memory"); 

  return retval;}
 
              因为该函数创建的是内核线程,由于可能创建出来的子线程与父线程的pid相同,因此无法通过pid的比较来区分内核线程,先将父线程的esp拷贝到esi,等调用完clone后,让子线程的esp与父线程esp比较,esp:内核线程如果不等将系统调用的函数所需要的参数根据(arg)关联到eax,然后入栈。call调用 函数 fn,运行完fn函数后系统调用sys_exit函数,直接退出。
例子:
  #include<linux/module.h>
#include<linux/sched.h>
#include<linux/pid.h>

static int my_thread( void * arg)
{
      printk("<0> in the kernel_threadfunction \n");
      printk("<0> the current pid is:%d\n",current->pid);
      return0;
}

static int __init  thread_kernel_init (void)
{
      intresult  ;
     
 
      printk("<0> intokernel_thread_init\n");
      result =kernel_thread(my_thread,NULL,CLONE_KERNEL);

      printk("<0> the kernel_thread resultis :%d\n",result);
      printk("<0> current pid is : %d\n",current->pid);
      printk("<0> outkernel_thread_init.\n");
      return0;
}
static void __exit thread_kernel_exit(void)
{
      printk("byethread_kernel");
}

module_init(thread_kernel_init);
module_exit(thread_kernel_exit);
结果:


kernel_thread <wbr>的实现 <wbr>、 <wbr>应用 <wbr>、分析

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值