Chinaunix首页 | 论坛 | 博客
  • 博客访问: 792424
  • 博文数量: 118
  • 博客积分: 2067
  • 博客等级: 大尉
  • 技术积分: 1751
  • 用 户 组: 普通用户
  • 注册时间: 2009-07-17 14:27
文章存档

2016年(1)

2013年(1)

2012年(3)

2011年(26)

2010年(47)

2009年(40)

分类: LINUX

2011-01-26 11:34:17


kthread_create与kernel_thread的区别

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

 

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


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

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

#include
#include
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创建线程:
    struct task_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函数,结束线程的运行。
    int kthread_stop(struct task_struct *thread);
kthread_stop() 通过发送信号给线程。
如果线程函数正在处理一个非常重要的任务,它不会被中断的。当然如果线程函数永远不返回并且不检查信号,它将永远都不会停止。
参考:Kernel threads made easy
--
view plaincopy to clipboardprint?
#include   
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);  

#include
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()的掌控之中,线程在退出时可以从容地释放资源,而不是莫名其妙地被人“暗杀”。

kthread_run函数 理解学习
最近发现在内核创建线程的时候经常会用到kthread_run()这样的一个调用。于是准备拿出来学习一下。首先看看它的定义之处才发现它是一个宏函数,而不是一个真正意义上的函数。在include/linux/Kthread.h里有/**
* kthread_run - create and wake a thread.
* @threadfn: the function to run until signal_pending(current).
* @data: data ptr for @threadfn.
* @namefmt: printf-style name for the thread.
*
* Description: Convenient wrapper for kthread_create() followed by
* wake_up_process(). Returns the kthread or ERR_PTR(-ENOMEM).
*/
#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;           \
})

这个函数的英文注释里很明确的说明: 创建并启动一个内核线程。可见这里的函数kthread_create()只是创建了内核线程,而最后启动是怎么启动的呢,我们看到了后面的wake_up_process()函数,没错就是这个函数启动了这个线程,让它在一开始就一直运行下去。知道遇见kthread_should_stop函数或者kthread_stop()函数。那我们具体看看前一个函数到底做了什么吧。

在这个宏里面主要是调用了函数:kthread_create()

这个函数是干什么的呢?在Kernel/Kthread.c里面我们可以看到:

/**
* kthread_create - create a kthread.
* @threadfn: the function to run until signal_pending(current).
* @data: data ptr for @threadfn.
* @namefmt: printf-style name for the thread.
*
* Description: This helper function creates and names a kernel
* thread. The thread will be stopped: use wake_up_process() to start
* it. See also kthread_run(), kthread_create_on_cpu().
*
* When woken, the thread will run @threadfn() with @data as its
* argument. @threadfn can either call do_exit() directly if it is a
* standalone thread for which noone will call kthread_stop(), or
* return when 'kthread_should_stop()' is true (which means
* kthread_stop() has been called). The return value should be zero
* or a negative error number; it will be passed to kthread_stop().
*
* Returns a task_struct or ERR_PTR(-ENOMEM).
*/
struct task_struct *kthread_create(int (*threadfn)(void *data),
       void *data,
       const char namefmt[],
       ...)
{
struct kthread_create_info create;
DECLARE_WORK(work, keventd_create_kthread, &create);

create.threadfn = threadfn;
create.data = data;
init_completion(&create.started);
init_completion(&create.done);

/*
* The workqueue needs to start up first:
*/
if (!helper_wq)
   work.func(work.data);
else {
   queue_work(helper_wq, &work);
   wait_for_completion(&create.done);
}
if (!IS_ERR(create.result)) {
   va_list args;
   va_start(args, namefmt);
   vsnprintf(create.result->comm, sizeof(create.result->comm),
     namefmt, args);
   va_end(args);
}

return create.result;
}
EXPORT_SYMBOL(kthread_create);

注意到上面的这段英文解释:说这个函数会创建一个名为namefmt的内核线程,这个线程刚创建时不会马上执行,要等到它将kthread_create() 返回的task_struct指针传给wake_up_process(),然后通过此函数运行线程。我们看到creat结构体,我们将传入的参数付给了它,而threadfn这个函数就是创建的运行函数。在使用中我们可以在此函数中调用kthread_should_stop()或者kthread_stop()函数来结束线程。这里我们看到创建线程函数中使用工作队列DECLARE_WORK,我们跟踪一下发现这只是将函数#define DECLARE_WORK(n, f, d)      \
struct work_struct n = __WORK_INITIALIZER(n, f, d)
然后再跟进:

#define __WORK_INITIALIZER(n, f, d) {     \
.entry = { &(n).entry, &(n).entry },    \
.func = (f),       \
.data = (d),       \
.timer = TIMER_INITIALIZER(NULL, 0, 0),    \
}

反正目的是创建一个工作组队列,而其中keventd_create_kthread()函数主要是起到创建线程的功能

/* We are keventd: create a thread. */
static void keventd_create_kthread(void *_create)
{
struct kthread_create_info *create = _create;
int pid;

/* We want our own signal handler (we take no signals by default). */
pid = kernel_thread(kthread, create, CLONE_FS | CLONE_FILES | SIGCHLD);
if (pid < 0) {
   create->result = ERR_PTR(pid);
} else {
   wait_for_completion(&create->started);
   read_lock(&tasklist_lock);
  create->result = find_task_by_pid(pid);
   read_unlock(&tasklist_lock);
}
complete(&create->done);
}
再看看kernel_thread()函数最后调用到了哪里:

/*
* Create a kernel thread.
*/
pid_t kernel_thread(int (*fn)(void *), void *arg, unsigned long flags)
{
struct pt_regs regs;
long pid;

memset(®s, 0, sizeof(regs));

regs.ARM_r1 = (unsigned long)arg;
regs.ARM_r2 = (unsigned long)fn;
regs.ARM_r3 = (unsigned long)do_exit;
regs.ARM_pc = (unsigned long)kernel_thread_helper;
regs.ARM_cpsr = SVC_MODE;

pid = do_fork(flags|CLONE_VM|CLONE_UNTRACED, 0, ®s, 0, NULL, NULL);

MARK(kernel_thread_create, "%ld %p", pid, fn);
return pid;
}
EXPORT_SYMBOL(kernel_thread);

好,最后我们看到了线程通过申请进程的pid号来被创建,关键是我们要知道如何使用这个宏函数,也就是如何应用它。要注意的是它调用了创建线程函数,同时也激活了线程。所以代码中调用了它的话就隐含着已经启动一个线程。


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