linux kernel synchronization 1

cat /proc/cpuinfo check all processors

ps -eaF the PSR shows process is runing on processor number

preemption

user space

Under Linux, user-space programs have always been preemptible: the kernel interrupts user-space programs to switch to other threads, using the regular clock tick.

kernel space

kernel preemption has been introduced in 2.6 kernels, and one can enable or disable it using the CONFIG_PREEMPT option.
Kernel preemption can occur:
​ When returning to kernel-space from an interrupt handler
​ When kernel code becomes preemptible again
​ If a task in the kernel explicitly calls schedule()
​ If a task in the kernel blocks (which results in a call to schedule())

processor id

smp_processor_id() gives you the current processor number on which kernel is running
在多处理器系统中,Linux内核调度器会动态地将线程调度到不同的CPU上运行,导致每次调用smp_processor_id()返回不同的值

点击查看代码
#include <linux/init.h>
#include <linux/module.h>
#include <linux/kdev_t.h>
#include <linux/fs.h>
#include <linux/cdev.h>
#include <linux/device.h>
#include<linux/slab.h>                 //kmalloc()
#include<linux/uaccess.h>              //copy_to/from_user()
#include <linux/kthread.h>             //kernel threads
#include <linux/sched.h>               //task_struct 
#include <linux/delay.h>
 
static struct task_struct *my_thread;
 
int thread_function(void *pv)
{
    int i=0;
    while(!kthread_should_stop()) {
        printk(KERN_INFO "Processor id:%d\t In Thread Function %d\n", smp_processor_id(), i++);
        msleep(1000);
    }
    return 0;
}
 
 
static int __init my_driver_init(void)
{
	pr_info("%s: processor id:%d\n", __func__, smp_processor_id());
	my_thread = kthread_create(thread_function,NULL,"myThread");
	if(my_thread) {
		wake_up_process(my_thread);
		return 0;
	} else {
		printk(KERN_ERR "Cannot create kthread\n");
		return -1;
	}
}
 
void __exit my_driver_exit(void)
{
        kthread_stop(my_thread);
        pr_info("%s:Device Driver Remove...Done\tProcessor Id:%d\n", __func__, smp_processor_id());
}
 
module_init(my_driver_init);
module_exit(my_driver_exit);
 
MODULE_LICENSE("GPL");

posted @ 2025-09-20 21:38  fangshuo  阅读(5)  评论(0)    收藏  举报