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

相关推荐
码出钞能力27 分钟前
linux内核模块的查看
linux·运维·服务器
星辰云-1 小时前
# Linux Centos系统硬盘分区扩容
linux·运维·centos·磁盘扩容
聽雨2371 小时前
02每日简报20250704
linux·科技·金融·生活·社交电子·娱乐·媒体
Maki Winster2 小时前
Peek-Ubuntu上Gif录制工具-24.04LTS可装
linux·ubuntu·peek
Maki Winster3 小时前
在 Ubuntu 下配置 oh-my-posh —— 普通用户 + root 各自使用独立主题(共享可执行)
linux·运维·ubuntu
守望时空333 小时前
Linux下KDE桌面创建自定义右键菜单
linux
l0sgAi3 小时前
vLLM在RTX50系显卡上部署大模型-使用wsl2
linux·人工智能
麟城Lincoln5 小时前
【RHCSA-Linux考试题目笔记(自用)】servera的题目
linux·笔记·考试·rhcsa
寻月隐君5 小时前
保姆级教程:Zsh + Oh My Zsh 终极配置,让你的 Ubuntu 终端效率倍增
linux·后端·命令行
XM-54585 小时前
2025微信小程序wxapkg解包全攻略
linux·运维·小程序