最近经常能看见kthread_create方法,于是:
运用场景:内核线程是工作在内核空间的,不属于任何一个进程,可以发生睡眠。可以用内核线程来进行一些循环的动作。
是独立运行在内核空间的标准进程且只能由其它的内核线程创建。
内核线程和普通的进程间的区别在于内核线程没有独立的地址空间,mm指针被设置为NULL;它只在内核空间运行,从来不切换到用户空间去;并且和普通进程一样,可以被调度,也可以被抢占。------(来源Linux内核线程-niao5929-ChinaUnix博客,侵删)
方法一:
与wake_up_process函数配套使用
static struct task_struct *my_task;
int threadfunc(void *data){
do{
set_current_state(TASK_UNINTERRUPTIBLE);
if(){//条件为真
//进行业务处理
}
else{//条件为假
//让出CPU运行其他线程,并在指定的时间内重新被调度
schedule_timeout(HZ); // 休眠,与set_current_state配合使用,需要计算,这里表示休眠一秒
}while(!kthread_should_stop())
static int init_module(void) //驱动加载函数
{
int err;
my_task= kthread_create(threadfunc, NULL, "test_task");
if(IS_ERR(my_task)){
printk("Unable to start kernel thread.\n");
err = PTR_ERR(my_task);
my_task=NULL;
return err;
}
wake_up_process(my_task);
return 0;
}
static void cleanup_module(void)
{
if(test_task){
kthread_stop(test_task);
test_task = NULL;
}
}
module_exit(cleanup_module);
module_init(init_module);
方法2:
kthread_run():区别就是kthread_run()封装了kthread_create+wake_up_process。但是这并不意味着kthread_run就比kthread_create好,如果创建的 thread 运行在指定的 cpu 上,就就必须用kthread_create+kthread_bind(绑定)+wake up。
static struct task_struct *test_kthread = NULL;
static int test_kthread_func(void) //定义一个内核线程要执行的函数
{
while (!kthread_should_stop()) {
//do somthing
msleep(5000);
}
return 0;
}
static __init int test_kthread_init(void)
{
test_kthread = kthread_run(test_kthread_func, NULL, "kthread-test");
if (!test_kthread) {
ERR("kthread_run fail");
return -ECHILD;
}
return 0;
}
static __exit void test_kthread_exit(void)
{
if (test_kthread) {
kthread_stop(test_kthread); //停止内核线程
test_kthread = NULL;
}
}
module_init(test_kthread_init);
module_exit(test_kthread_exit);