kthread_create():创建线程。
struct task_struct *kthread_create(int (*threadfn)(void *data),void *data,const char *namefmt, ...);//注意,第二个参数data用于向线程传递参数
#define kthread_run(threadfn, data, namefmt, ...) \
({ \
struct task_struct *__k \
= kthread_create(threadfn, data, namefmt, ## __VA_ARGS__); \
if (!IS_ERR(__k)) \
wake_up_process(__k); \
__k; \
})
kthread_run是一个宏定义,功能是创建并启动内核线程。
线程创建后,不会马上运行,而是需要将kthread_create() 返回的task_struct指针传给wake_up_process(),然后通过此函数运行线程。
这两个函数的区别就是 kthread_run() 函数中封装了前者,由 kthread_create() 创建的 thread 不会立即运行,而后者创建的 thread 会立刻运行,原因是在 kthread_run() 中调用了 wake_up_process().用什么函数看你自己的需求,如果你要让你创建的 thread 运行在指定的 cpu 上那必须用前者(因为它创建的 thread 不会运行),然后再用 kthread_bind() 完成绑定,最后 wake up.
例如:
static struct task_struct *test_task;
static int test_init_module(void) //驱动加载函数
{
int err;
test_task = kthread_create(threadfunc, NULL, "test_task");
if(IS_ERR(test_task)){
printk("Unable to start kernel thread.\n");
err = PTR_ERR(test_task);
test_task =NULL;
return err;
}
kthread_bind(test_task,2)//将线程绑定到core2上
wake_up_process(test_task);//唤醒线程
return 0;
}
module_init(test_init_module);
参考链接:
https://blog.csdn.net/quincyfang/article/details/50426491
https://blog.csdn.net/u012248972/article/details/81703583
线程退出:
kthread_stop:通过发送信号给线程,使之退出。
int kthread_stop(struct task_struct *thread);
线程一旦启动起来后,会一直运行,除非该线程主动调用do_exit函数,或者其他的进程调用kthread_stop函数,结束线程的运行。
但如果线程函数正在处理一个非常重要的任务,它不会被中断的。当然如果线程函数永远不返回并且不检查信号,它将永远都不会停止。
https://blog.csdn.net/iamliuyanlei/article/details/9326119