get_cpu_var,put_cpu_var不更新每个CPU变量

时间:2019-05-12 09:40:29

标签: c linux linux-kernel

从书中读取后,我试图为Per CPU变量编写示例代码,但是更新计数器之一的per cpu变量后,我无法获得预期的输出。

#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/delay.h>

MODULE_LICENSE("GPL");
DEFINE_PER_CPU(int, counter);
static int test_percpu_init(void)
{
    int num_cpus = num_online_cpus();
    int i = 0;
    int val;

    pr_info("Number of cpus available:%d\n", num_cpus);
    for (i = 0; i < num_cpus; i++) {
        int value = per_cpu(counter, i);
        pr_info("Value of counter is %d at Processor:%d\n", value, i);
    }

    val = get_cpu_var(counter);
    val = 10;
    put_cpu_var(counter);

    pr_info("Printing counter value of all processor after updating current processor:%d\n",
            smp_processor_id());

    for (i = 0; i < num_cpus; i++) {
        int value = per_cpu(counter, i);
        pr_info("Value of counter is %d at Processor:%d\n", value, i);
    }


    return 0;
}

static void test_percpu_exit(void)
{
}

module_init(test_percpu_init);
module_exit(test_percpu_exit);

dmesg输出:

[14516.661529] Number of cpus available:6
[14516.661531] Value of counter is 0 at Processor:0
[14516.661532] Value of counter is 0 at Processor:1
[14516.661532] Value of counter is 0 at Processor:2
[14516.661533] Value of counter is 0 at Processor:3
[14516.661533] Value of counter is 0 at Processor:4
[14516.661534] Value of counter is 0 at Processor:5
[14516.661534] Printing counter value of all processor after updating current processor:5
[14516.661534] Value of counter is 0 at Processor:0
[14516.661535] Value of counter is 0 at Processor:1
[14516.661535] Value of counter is 0 at Processor:2
[14516.661536] Value of counter is 0 at Processor:3
[14516.661536] Value of counter is 0 at Processor:4
[14516.661536] Value of counter is 0 at Processor:5

请您看看,为什么当前处理器的值没有更新。我在使用API​​或传递任何错误的参数时犯了任何错误。

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

get_cpu_var左值的形式返回给定CPU上的每个CPU变量,也就是说,可以将其视为非常简单的变量

// read per-CPU variable counter
int value = get_cpu_var(counter);
// write per-CPU variable counter
get_cpu_var(counter) = 10;
// get a pointer to per CPU variable
int* p_counter = &get_cpu_var(counter);
// read per-CPU variable via a pointer
int value = *p_counter;
// write per-CPU variable via a pointer
*p_counter = 10;