kthread_run 示例
时间: 2024-12-14 19:15:20 浏览: 65
`kthread_run()`是Linux内核中用于启动一个新的线程(也称为KThread,即Kernel Thread)的函数。它通常用于创建后台任务,这些任务可以在独立的上下文中运行而不会阻塞主线程。下面是一个简单的`kthread_run()`示例:
```c
#include <linux/kthread.h>
#include <linux/init.h>
static int __init my_thread_func(void *data)
{
printk(KERN_INFO "My custom thread function started.\n");
// 这里放你的线程实际要执行的代码
return 0;
}
static struct task_struct *my_thread;
module_init(my_module_init) {
my_thread = kthread_create(my_thread_func, NULL, "my_thread_name");
if (IS_ERR(my_thread)) {
printk(KERN_ERR "Failed to create thread: %ld\n", PTR_ERR(my_thread));
return -ENOMEM;
}
int ret = kernel_thread_runner(my_thread);
if (ret != 0) {
printk(KERN_ERR "Thread start failed: %d\n", ret);
put_task_struct(my_thread);
return ret;
}
printk(KERN_INFO "Thread created successfully with PID %d.\n", task_pid(my_thread));
return 0;
}
module_exit(my_module_exit) {
printk(KERN_INFO "Cleaning up thread resources...\n");
stop_thread(my_thread); // 停止线程
wait_for_completion(&my_thread->completion); // 等待线程结束
put_task_struct(my_thread); // 释放资源
printk(KERN_INFO "Thread cleaned up.\n");
}
阅读全文
相关推荐



















