内核线程

创建内核线程由内核线程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或多核心,才会多线程同时跑

posted @ 2016-07-13 00:37  thomas_blog  阅读(127)  评论(0编辑  收藏  举报