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

相关推荐
Jia ming28 分钟前
从打补丁到一行配置:PREEMPT_RT 主线化之后,实时内核到底该怎么配?
linux
杨云龙UP30 分钟前
MySQL Host is blocked because of many connection errors 导致 JDBC 连接失败排查与解决
linux·运维·网络·数据库·sql·mysql·登录失败
企鹅的蚂蚁1 小时前
LubanCat RK3588 实时 Linux 开发(九):从 U-Boot 到 initramfs 的串口启动故障分析
linux·rk3588·u-boot·串口调试·initramfs·linux启动
kkkkkkkkkk_Z2 小时前
学嵌入式和Linux应用编程|学习日记:UDP协议与Wireshark抓包学习笔记
linux·笔记·学习
嵌入式小能手2 小时前
飞凌嵌入式ElfBoard-Shell编程应用实例-提取字符并设置rtc时间
linux
刃神太酷啦2 小时前
Redis 核心进阶:哨兵、集群、缓存问题与分布式锁详解----《Hello Redis!》(6)
linux·c语言·数据库·c++·redis·分布式·缓存
大卡片2 小时前
LCD相关知识
linux
闲云野鹤在人间2 小时前
Docker入门|第3章 镜像详解
linux·网络·docker·容器·centos·云计算·php
小卿噢3 小时前
malloc 成功 ≠ 你有内存:一次把 OOM 从头测到尾
linux·后端
团子股股东峥哥3 小时前
day38-RHEL-管理存储堆栈
linux·运维·服务器