创建线程kthread_create

57 篇文章 4 订阅

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值