linux 内核线程

linux 内核线程,第1张

创建内核线程:
 struct task_struct *kthread_create(int (*threadfn)(void *data),
   void *data, const char namefmt[]);
 
唤醒内核线程(可以唤醒所有进程(线程)):
 wake_up_process(struct task_struct *k);

创建并运行内核线程:
 struct task_struct *kthread_run(int (*threadfn)(void *data),
   void *data, const char namefmt[]);

通知内核线程停止:
 int kthread_stop(struct task_struct *k);
 返回threadfn函数的返回值, 如果k没有被wake_up_process(k)过将返回-EINTR
 不是强制停止, 如果内核线程不停止将一直等待

检查是否收到停止信号:
 int kthread_should_stop(void);

kthread_create与kernel_thread的区别

从表面上来看,这两个函数非常的类似,但是实现却是相差甚远。
kthread_create是通过work_queue来实现的,kernel_thread是通过do_fork来实现的。

 

kernel thread可以用kernel_thread创建,但是在执行函数里面必须用daemonize释放资源并挂到init下,还需要用 completion等待这一过程的完成。


kthread_create是比较正牌的创建函数,这个不必要调用daemonize,用这个创建的kernel thread都挂在了kthread线程下。

 

 

 

 

可以在非内核线程中调用kernel_thread, 但这样创建的线程必须在自己调用daemonize(...)来释放资源,成为真正的内核线程。

#include <linux/kernel.h>
#include <linux/module.h>
static int noop(void *dummy)
{
        int i = 0;
        daemonize("mythread");
        while(i++ < 5) {
                printk("current->mm = %p\n", current->mm);
                printk("current->active_mm = %p\n", current->active_mm);
                set_current_state(TASK_INTERRUPTIBLE);
                schedule_timeout(10 * HZ);
        }
        return 0;
}
static int test_init(void)
{
        kernel_thread(noop, NULL, CLONE_KERNEL | SIGCHLD);
        return 0;
}
static void test_exit(void) {}
module_init(test_init);
module_exit(test_exit);

”mythread“就是给这个内核线程取的名字, 可以用ps -A来查看。
schedule()用于进程调度, 可以理解为放弃CPU的使用权.

 

 

 

 

 kthread_create创建线程

1 使用kthread_create创建线程:
    struct task_struct *kthread_create(int (*threadfn)(void *data),

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/zaji/2084322.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-07-22
下一篇2022-07-22

发表评论

登录后才能评论

评论列表(0条)

    保存