Linux创建内核线程

Linux创建内核线程

1、创建并启动一个内核线程

struct task_struct *kthread_create(int (*threadfn)(void *data),
                               void *data,
                               const char namefmt[], ...);
/**
 * kthread_run - create and wake a thread.
 * @threadfn: the function to run until signal_pending(current).
 * @data: data ptr for @threadfn.
 * @namefmt: printf-style name for the thread.
 *
 * Description: Convenient wrapper for kthread_create() followed by
 * wake_up_process().  Returns the kthread or ERR_PTR(-ENOMEM).
 */
#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_create()只是创建一个内核线程,但并没有启动,需要调用wake_up_process()来启动线程,所以内核又帮我们定义了一个宏kthread_run来帮我们搞定。内核线程创建成功后,会返回一个struct task_struct对象指针,方便我们的后续操作。

2、关闭一个线程

int kthread_stop(struct task_struct *k);

这个调用是会阻塞等待,直到内核线程k退出为止。原因为此函数内部会调用wait_for_completion()的方法(通过等待队列来实现),阻塞等待内核线程自身的退出。

3、内核线程函数,如何判断自身需要退出:

 int kthread_should_stop(void);

如果该内核线程已经被设置stop标志了,则会返回1,否则返回0。

举例:

#include <linux/kthread.h>
static struct task_struct *sr501_kthread;

#if 0
sr501_kthread = kthread_create(sr501_thread, NULL, "sr501d");
wake_up_process(sr501_kthread);
#else
sr501_kthread  =kthread_run(kthread_test_func, NULL, "kthread-test");  
//创建线程kthread-test,并且运行

//停止线程
kthread_stop(sr501_kthread);

//内核线程函数实例
static int sr501_thread(void *data)
{
	int val;
	int pre = -1;
	while (1)
	{
		//此处添加业务逻辑
		//这两行代码让创建的系统线程进入休眠,时间为1HZ
		set_current_state(TASK_INTERRUPTIBLE);
		schedule_timeout(HZ);
		//在 kthread_should_stop() 检测到线程需要停止时,调用set_current_state(TASK_RUNNING) 	是为了确保线程状态被正确设置。即使线程要退出,也必须确保线程处于“运行”状态,以便调度器能够正确处理线程状态。
		if (kthread_should_stop()) {
			set_current_state(TASK_RUNNING);
			break;
		}
	}
	return 0;
}
#endif
  • 5
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值