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秒打印一次信息。在模块卸载时,线程被停止并清理。

相关推荐
小小小糖果人24 分钟前
Linux云计算基础篇(27)-NFS网络文件系统
linux·网络·云计算
小小小糖果人29 分钟前
Linux云计算基础篇(25)-DNS配置
linux·运维·云计算
TIANE-Kimmy41 分钟前
VS code定时任务设置(mac os)
linux·运维·服务器
大聪明-PLUS43 分钟前
嵌入式Linux简介—第二部分(共3部分)
linux·嵌入式·arm·smarc
panshiyangmaye1 小时前
RHCSA作业1
linux·运维·服务器
egoist20231 小时前
[linux仓库]信号保存[进程信号·肆]
linux·开发语言·信号集·信号保存·sigpending
keep intensify1 小时前
Redis基础指令全解析:从入门到精通
linux·数据库·c++·redis
Industio_触觉智能1 小时前
RK3562核心板/开发板RT-Linux系统实时性及硬件中断延迟测试
linux·嵌入式开发·瑞芯微·rk3562·rt linux·xenomai rt·preempt_rt
爱吃生蚝的于勒1 小时前
【Linux】零基础学会linux环境基础开发工具使用(yum,vim,makefile,gdb)
linux·服务器·数据结构·c++·蓝桥杯·编辑器·vim
本贾尼1 小时前
Linux系统下的终端,会话,shell,bash,进程组这几个概念的关系。
linux·服务器·网络·ubuntu·bash