struct task_struct *kthread_create(int (*threadfn)(void *data),void *data, const char namefmt[], ...)
功能:创建一个内核线程
threadfn:线程运行的函数
data:传递给线程函数的参数
namefmt: 进程名 在task->comm中保存此字符串
头文件: #include <linux/kthread.h>
注意:此函数创建的线程不会马上进入运行 需要使用 wake_up_process(task);来唤醒线程运行
int kthread_should_stop(void)
功能:返回should_stop标志,线程是否停止
头文件: #include <linux/kthread.h>
int kthread_stop(struct task_struct *k)
功能:停止线程设置should_stop标志位1
k:停止的线程
头文件: #include <linux/kthread.h>
例子如下:
#include <linux/module.h>
#include <linux/init.h>#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/sched.h>
#include <linux/kthread.h>
struct task_struct *ptsk = NULL;
//线程回调函数
int pthread_fun(void *data)
{
long outtime;
while(!kthread_should_stop())//线程是否停止,通过kthread_stop()来停止设置kthread->should_stop为1
{
set_current_state(TASK_UNINTERRUPTIBLE);//设置当前的进程状态为休眠状态(包括TASK_UNINTERRUPTIBLE和TASK_INTERRUPTIBLE)
printk("**************hello world\n");
outtime = schedule_timeout(HZ*2);//让出cpu2秒超时后 在获得cpu即在指定的时间到期后(timeout了)将进程唤醒
printk("******************outtime=%ld\n",outtime);
}
return 0;
}
static int __init yld_init(void)
{
//创建一个内核线程
ptsk = kthread_create(pthread_fun,NULL,"testpt");
if(IS_ERR(ptsk))
{
printk("Create thread is error\n");
return -1;
}
//新建的线程是没有运行的通过wake_up_process唤醒该线程
wake_up_process(ptsk);
return 0;
}
static void __exit yld_exit(void)
{
//停止线程设置kthread->should_stop为1
kthread_stop(ptsk);
return;
}
module_init(yld_init);
module_exit(yld_exit);
MODULE_LICENSE("GPL");