Linux内核 - kthread_stop总是返回-EINTR?

时间:2017-07-15 20:30:10

标签: c linux multithreading kernel

我正在对Linux kthread函数进行一些测试,并有以下模块:

#include <linux/module.h>
#include <linux/kthread.h>
#include <linux/sched.h>
#include <linux/smp.h>
#include <linux/cpumask.h>
#include <linux/err.h>

MODULE_LICENSE("GPL");

int function(void *data)
{
    printk(KERN_DEBUG "CPU: %u\n", smp_processor_id());

    return 0;
}

/* Function executed upon loading driver */
int __init init_module(void)
{
    unsigned int cpu;

    printk(KERN_DEBUG "init\n");

    for_each_present_cpu(cpu)
    {
        struct task_struct *thread = kthread_create(function, NULL, "Thread %u", cpu);

        if (!IS_ERR(thread))
        {
            int result;

            /* Bind the thread to the current core */
            kthread_bind(thread, cpu);

            /* Start the thread */
            wake_up_process(thread);

            /* Wait for the thread function to complete */
            result = kthread_stop(thread);

            printk(KERN_DEBUG "Thread %u stopped with result %d\n", cpu, result);
        }
        else
        {
            printk(KERN_ALERT "Could not create a thread bound to core number %u\n", cpu);
            break;
        }
    }

    return 0;
}

/* Function executed when unloading module */
void cleanup_module(void)
{
    printk(KERN_DEBUG "exit\n");
}

根据我的理解,我应该能够在init_module结束之前看到所有“CPU:...”打印。但是,kthread_stop总是返回-EINTR,就好像实际上没有调用wake_up_process一样。我做错了什么?

1 个答案:

答案 0 :(得分:1)

一个有根据的猜测:加载模块的线程永远不会放弃它运行的cpu,所以特别是你绑定到这个cpu的线程永远不会有机会在第一时间运行。发生这种情况是因为禁用了内核抢占(请参阅CONFIG_PREEMPT)。尝试绑定到不同的cpu或屈服。