• kthread_create使用demo


    最近经常能看见kthread_create方法,于是:

    运用场景:内核线程是工作在内核空间的,不属于任何一个进程,可以发生睡眠。可以用内核线程来进行一些循环的动作。

    是独立运行在内核空间的标准进程且只能由其它的内核线程创建。

    内核线程和普通的进程间的区别在于内核线程没有独立的地址空间,mm指针被设置为NULL;它只在内核空间运行,从来不切换到用户空间去;并且和普通进程一样,可以被调度,也可以被抢占。------(来源Linux内核线程-niao5929-ChinaUnix博客,侵删)

    方法一:

    与wake_up_process函数配套使用

    1. static struct task_struct *my_task;
    2. int threadfunc(void *data){
    3. do{
    4. set_current_state(TASK_UNINTERRUPTIBLE);
    5. if(){//条件为真
    6. //进行业务处理
    7. }
    8. else{//条件为假
    9. //让出CPU运行其他线程,并在指定的时间内重新被调度
    10. schedule_timeout(HZ); // 休眠,与set_current_state配合使用,需要计算,这里表示休眠一秒
    11. }while(!kthread_should_stop())
    12. static int init_module(void) //驱动加载函数
    13. {
    14. int err;
    15. my_task= kthread_create(threadfunc, NULL, "test_task");
    16. if(IS_ERR(my_task)){
    17. printk("Unable to start kernel thread.\n");
    18. err = PTR_ERR(my_task);
    19. my_task=NULL;
    20. return err;
    21. }
    22. wake_up_process(my_task);
    23. return 0;
    24. }
    25. static void cleanup_module(void)
    26. {
    27. if(test_task){
    28. kthread_stop(test_task);
    29. test_task = NULL;
    30. }
    31. }
    32. module_exit(cleanup_module);
    33. 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。

    1. static struct task_struct *test_kthread = NULL;
    2. static int test_kthread_func(void) //定义一个内核线程要执行的函数
    3. {
    4. while (!kthread_should_stop()) {
    5. //do somthing
    6. msleep(5000);
    7. }
    8. return 0;
    9. }
    10. static __init int test_kthread_init(void)
    11. {
    12. test_kthread = kthread_run(test_kthread_func, NULL, "kthread-test");
    13. if (!test_kthread) {
    14. ERR("kthread_run fail");
    15. return -ECHILD;
    16. }
    17. return 0;
    18. }
    19. static __exit void test_kthread_exit(void)
    20. {
    21. if (test_kthread) {
    22. kthread_stop(test_kthread); //停止内核线程
    23. test_kthread = NULL;
    24. }
    25. }
    26. module_init(test_kthread_init);
    27. module_exit(test_kthread_exit);

  • 相关阅读:
    MySQL数据库增删改查进阶(联合查询聚合查询)
    电脑重装系统后如何把网站设为首页
    【Linux】OS和进程概念
    7 矩阵中战斗力最弱的 K 行
    手机用Postern配置socks5全局代理详细教程
    [JavaWeb]—Mybatis入门
    FeignClient注解中各种属性详解二
    Mysql Explain 详解(荣耀典藏版)
    培训机构如何利用小程序提升服务质量
    Service Mesh之Istio部署bookinfo
  • 原文地址:https://blog.csdn.net/witch23333/article/details/133063856