内核线程

本文详细介绍了内核线程的创建、终止及绑定CPU的方法。通过kthreadd线程循环处理待创建任务,利用kthread_run等宏实现线程启动,并提供了手动停止线程的途径。此外还讨论了不同CPU状态映射的概念及其作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

创建内核线程由内核线程kthreadd完成

rest_init->kthreadd->create_kthread->kernel_thread->do_fork
int kthreadd(void *unused)
{
    for(;;)
    {
        if (list_empty(&kthread_create_list))
            schedule();

        spin_lock(&kthread_create_lock);
        while (!list_empty(&kthread_create_list))
        {
            struct kthread_create_info *create;

            create = list_entry(kthread_create_list.next,
                        struct kthread_create_info, list);
            list_del_init(&create->list);
            spin_unlock(&kthread_create_lock);

            create_kthread(create);

            spin_lock(&kthread_create_lock);
        }
        spin_unlock(&kthread_create_lock);
    }

    return 0;
}

创建

#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; \
})
struct task_struct *kthread_create(int (*threadfn)(void *data), void *data, const char namefmt[], ...) 
__attribute__((format(printf, 3, 4)));

终止

int kthread_stop(struct task_struct *k)
{
    kthread->should_stop = 1;
}
int kthread_should_stop(void) //子线程退出条件
{
    return to_kthread(current)->should_stop;
}

终止子线程需要手动置1使子线程退出循环

绑定CPU

void kthread_bind(struct task_struct *p, unsigned int cpu)

提高内核线程的工作效率

查看CPU

#define cpu_possible_map    (*(cpumask_t *)cpu_possible_mask)
#define cpu_online_map      (*(cpumask_t *)cpu_online_mask)
#define cpu_present_map     (*(cpumask_t *)cpu_present_mask)
#define cpu_active_map      (*(cpumask_t *)cpu_active_mask)

cpu_possible_map:
最多有多少个CPU,包括本机的CPU,以及可以热插拔的CPU
1. 假设cpu_possible_map为10,本机CPU个数为8个,则最多可以再添加2个可插拔CPU
cpu_present_map:
当前有多少个CPU
1. 本机CPU个数为8个,都是online的,则cpu_present_map为8
2. 再插入1个可插拔CPU,则cpu_present_map为9
cpu_online_map:
在当前的CPU中,有多少个可用的CPU
1. 本机CPU个数为8个,都是online的,则cpu_online_map为8
2. 将其中一个设置为offline,则cpu_online_map变为7

#define for_each_possible_cpu(cpu) for_each_cpu((cpu), cpu_possible_mask)
#define for_each_online_cpu(cpu)   for_each_cpu((cpu), cpu_online_mask)
#define for_each_present_cpu(cpu)  for_each_cpu((cpu), cpu_present_mask)

总结
线程是跑在CPU上的,如果是单CPU单核,那么主子线程只能有一个在跑;除非是多CPU或多核心,才会多线程同时跑

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值