kthread_create使用demo

最近经常能看见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);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值