现在的位置: 首页 > 综合 > 正文

Linux内核:kthread_create(线程)、SLEEP_MILLI_SEC

2018年10月02日 ⁄ 综合 ⁄ 共 1376字 ⁄ 字号 评论关闭

一、代码

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/kthread.h>
#include <linux/err.h>


MODULE_VERSION("1.0.0_0");
MODULE_LICENSE("GPL");
MODULE_AUTHOR("gwy");



#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


struct task_struct* thread = NULL;

void thread_proc(void* arg)
{
    struct timespec ts;  

    //set_current_state(TASK_UNINTERRUPTIBLE);
    while(!kthread_should_stop())
    {
        ts = current_kernel_time();  
        printk("thread_proc:%s. time:%ld\n", (char*)arg, ts.tv_sec);
        
        SLEEP_MILLI_SEC(1000);
    }
}

static int init_marker(void)
{
    int err;

    printk("init marker.\n");

    thread = kthread_create(thread_proc, "thread arg", "my_thread%d", 0);
    if (IS_ERR(thread))
    {
        err = PTR_ERR(thread);
        printk("kthread_create fail.\n");
        return err;
    }

    wake_up_process(thread);

    printk("thread create.\n");

    return 0;
}

static void exit_marker(void)
{
    if (thread)
    {
        kthread_stop(thread);
        thread = NULL;
        printk("thread stop.\n");
    }

    printk("exit marker.\n");
}


module_init(init_marker);
module_exit(exit_marker);

二、输出结果

三、注意

        1)在调用kthread_stop函数时,线程函数不能已经运行结束。否则,kthread_stop函数会一直进行等待。

        2)线程函数必须能让出CPU,以便能运行其他线程。  同时线程函数也必须能重新被调度运行。

        3)注意线程函数的使用,参见“kthread_create的简单使用”。

参考资料:

        kthread_create的简单使用:http://blog.csdn.net/newnewman80/article/details/7050090

        kthread_create与kerne_thread的区别:http://blog.sina.com.cn/s/blog_5a1e1b770100jfc0.html

抱歉!评论已关闭.