Linux内核 -- 多线程之kthread的使用

在 Linux 内核中创建并使用内核线程

本文档介绍如何在 Linux 内核中创建并使用一个内核线程(kthread)。

定义线程函数

线程函数是内核线程运行时执行的函数。它通常是一个无限循环,直到某种条件使其退出。

c 复制代码
#include <linux/kthread.h>
#include <linux/delay.h>
#include <linux/module.h>

static struct task_struct *thread_st;

static int thread_fn(void *data) {
    while (!kthread_should_stop()) {
        pr_info("Thread is running\n");
        ssleep(5); // Sleep for 5 seconds
    }
    pr_info("Thread is stopping\n");
    return 0;
}

创建和启动内核线程

你可以在模块初始化函数中创建并启动内核线程。

c 复制代码
static int __init init_thread(void) {
    pr_info("Creating thread\n");
    thread_st = kthread_create(thread_fn, NULL, "my_thread");
    if (thread_st) {
        wake_up_process(thread_st);
    } else {
        pr_err("Thread creation failed\n");
    }
    return 0;
}

停止内核线程

在模块退出函数中停止并清理内核线程。

c 复制代码
static void __exit cleanup_thread(void) {
    if (thread_st) {
        kthread_stop(thread_st);
        pr_info("Thread stopped\n");
    }
}

模块初始化和清理函数

定义模块的初始化和清理函数,并注册为内核模块。

c 复制代码
module_init(init_thread);
module_exit(cleanup_thread);

MODULE_LICENSE("GPL");
MODULE_AUTHOR("Your Name");
MODULE_DESCRIPTION("A simple example of creating a kthread");

完整代码

c 复制代码
#include <linux/kthread.h>
#include <linux/delay.h>
#include <linux/module.h>

static struct task_struct *thread_st;

static int thread_fn(void *data) {
    while (!kthread_should_stop()) {
        pr_info("Thread is running\n");
        ssleep(5); // Sleep for 5 seconds
    }
    pr_info("Thread is stopping\n");
    return 0;
}

static int __init init_thread(void) {
    pr_info("Creating thread\n");
    thread_st = kthread_create(thread_fn, NULL, "my_thread");
    if (thread_st) {
        wake_up_process(thread_st);
    } else {
        pr_err("Thread creation failed\n");
    }
    return 0;
}

static void __exit cleanup_thread(void) {
    if (thread_st) {
        kthread_stop(thread_st);
        pr_info("Thread stopped\n");
    }
}

module_init(init_thread);
module_exit(cleanup_thread);

MODULE_LICENSE("GPL");
MODULE_AUTHOR("Your Name");
MODULE_DESCRIPTION("A simple example of creating a kthread");

这段代码展示了如何在内核模块中创建和使用一个内核线程。初始化模块时,线程被创建并启动,运行时每隔5秒打印一次信息。在模块卸载时,线程被停止并清理。

相关推荐
晓13132 小时前
第七章 【C语言篇:文件】 文件全面解析
linux·c语言·开发语言
唐装鼠2 小时前
Linux 下 malloc 内存分配机制详解
linux·malloc
予枫的编程笔记2 小时前
【Linux入门篇】Linux运维必学:Vim核心操作详解,告别编辑器依赖
linux·人工智能·linux运维·vim操作教程·程序员工具·编辑器技巧·新手学vim
17(无规则自律)2 小时前
深入浅出 Linux 内核模块,写一个内核版的 Hello World
linux·arm开发·嵌入式硬件
中二病码农不会遇见C++学姐3 小时前
Linux下的.run文件
linux
予枫的编程笔记3 小时前
【Linux入门篇】摆脱权限混乱困境:Linux用户组管理+sudo提权,一步到位
linux·linux运维·后端开发·linux用户管理·linux权限配置·chmod命令·sudo配置
一个人旅程~3 小时前
Dell n4020双系统分区步骤和linux优化操作
linux·windows·电脑
忆~遂愿3 小时前
CANN metadef 深度解析:动态形状元数据管理、图编译器接口规范与序列化执行机制
大数据·linux
予枫的编程笔记3 小时前
【Linux入门篇】Linux文件操作不用记满屏命令,掌握touch/cp/mv核心用法就够了
linux·tar·linux命令·tail·cat·linux文件管理·linux新手教程
learning-striving3 小时前
kali连不上网解决方法
linux·开发语言·网络·php·kali