Thursday, December 19, 2013

Linux: Example of per CPU variables

In any kernel module that you are building, try this out. Depending on which core the function is invoked from, different variables will get incremented, changing the prints.

#include <linux/percpu.h>
DEFINE_PER_CPU(int, mypcint);
int test_percpu(void);
/* Increments the counter only on the current valid CPU */
int test_percpu()
    int i;
    per_cpu(mypcint, smp_processor_id()) = 0;
    per_cpu(mypcint, smp_processor_id())++;
    printk("%s(%d):===================================== \n", __FUNCTION__, __LINE__);
    for (i = 0; i <2; i++)
        printk("CPU %d | mycpint: %d ", i, per_cpu(mypcint, i));
    return 0;
This example can be invoked from any kernel module.


Post a Comment