The PER-CPU variable is a very interesting feature of the Linux kernel, and he assigns a copy of the variable to each processor in the system. The advantage of this is that in a multiprocessor system, when a processor operates on a copy of his variable, there is no need to consider competing with other processors, and the replica can take advantage of the processor's local hardware to improve access speed.
Based on the above characteristics of PER-CPU, its most typical use is in statistical counting. For example, in a network system, the kernel needs to keep track of the number of packets that have been received, and these numbers are updated very quickly in the system, possibly thousands of times per second. At this point, you can take advantage of the PER-CPU variable so that each processor in the system uses its own copy of the variable, so that the variable is updated without having to consider the problem of multiprocessor locking, which can improve performance.
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
# Include <asm/io.h>
#include <asm/uaccess.h>
#include <linux/percpu.h>
static int * PTR ;
static int __init hello_init (void)
{
int cpu;
int * THE_PTR;
ptr = alloc_percpu (int);
FOR_EACH_POSSIBLE_CPU (CPU) {/
* Shut down kernel can preempt * *
get_cpu ();
/* Get a specific CPU copy of the data pointer
/the_ptr = Per_cpu_ptr (ptr, CPU);
*the_ptr = CPU;
PRINTK ("val =%d\n", *the_ptr);
Put_cpu ();
}
return 0;
}
static void __exit hello_exit (void)
{
free_percpu (PTR);/* Free space */
}
module_init (hello_init);
Module_exit (hello_exit);
Module_author ("Tian bei");
Module_description ("Per_cpu_ptr test");
Module_license ("GPL");