kthread_create:创建线程。
struct
线程创建后,不会马上运行,而是需要将kthread_create()
kthread_run
struct
kthread_stop:通过发送信号给线程,使之退出。
int
线程一旦启动起来后,会一直运行,除非该线程主动调用do_exit函数,或者其他的进程调用kthread_stop函数,结束线程的运行。
但如果线程函数正在处理一个非常重要的任务,它不会被中断的。当然如果线程函数永远不返回并且不检查信号,它将永远都不会停止。
1.
#include <linux/sched.h>
#include <linux/kthread.h> //kthread_create()、kthread_run()
#include <err.h> //IS_ERR()、PTR_ERR()
2.
2.1创建线程
kernel thread可以用kernel_thread创建,但是在执行函数里面必须用daemonize释放资源并挂到init下,还需要用completion等待这一过程的完成。为了简化操作kthread_create闪亮登场。在模块初始化时,可以进行线程的创建。使用下面的函数和宏定义:
struct task_struct *kthread_create(int (*threadfn)(void *data),
kthread_create源码详解见http://blog.sina.com.cn/s/blog_6237dcca0100gq67.html
#define kthread_run(threadfn, data, namefmt, ...)
({
})
例如:
static struct task_struct *test_task;
static int test_init_module(void)
{
}
2.2线程函数
在线程函数里,完成所需的业务逻辑工作。主要框架如下所示:
int threadfunc(void *data){
}
2.3结束线程
在模块卸载时,可以结束线程的运行。使用下面的函数:
int kthread_stop(struct task_struct *k);
例如:
{
}
module_exit(test_cleanup_module);
3.
(1)
(2)
4.性能测试
可以使用top命令来查看线程(包括内核线程)的CPU利用率。命令如下:
可以使用下面命令来查找线程号:
代码:
#include
#ifndef
#define
do
long
while(timeout
{
timeout
}
}while(0);
#endif
static
static
{
char
memset(mydata,'\0',strlen(data)+1);
strncpy(mydata,data,strlen(data));
while(!kthread_should_stop())
{
SLEEP_MILLI_SEC(1000);
printk("%s\n",mydata);
}
kfree(mydata);
return
}
static
{
MyThread
return
}
static
{
if(MyThread)
{
printk("stop
kthread_stop(MyThread);
}
}
module_init(init_kthread);
module_exit(exit_kthread);
MODULE_AUTHOR("YaoGang");
这个内核线程的作用就是每隔一秒打印一个“hello
值得一提的是kthread_should_stop函数,我们需要在开启的线程中嵌入该函数并检查此函数的返回值,否则kthread_stop是不起作用的......