smp_processor_id——获取当前执行cpu_id

本文详细介绍了smp_processor_id()函数的功能,该函数用于获取当前执行的CPU ID,对于理解并行处理和多核架构下的进程调度具有重要作用。
// cpu0_stress.c #include <linux/module.h> #include <linux/kernel.h> #include <linux/sched.h> #include <linux/kthread.h> #include <linux/delay.h> static struct task_struct *stress_task = NULL; static int stress_cpu0(void *data) { // 输出启动信息 printk(KERN_INFO "cpu0_stress: Thread running on CPU #%d\n", raw_smp_processor_id()); // 等待几秒再开始忙循环 ssleep(2); while (!kthread_should_stop()) { int i; for (i = 0; i < 1000000; ++i) { volatile double d = 3.14159265; d *= d + 1.0; cpu_relax(); // 提示 CPU 可以节省功耗或让出流水线 } cond_resched(); // 主动让出调度器,防止被 watchdog 杀掉 } printk(KERN_INFO "cpu0_stress: Thread stopped.\n"); return 0; } static int __init cpu0_stress_init(void) { // 创建内核线程 stress_task = kthread_create(stress_cpu0, NULL, "cpu0_stress"); if (IS_ERR(stress_task)) { printk(KERN_ERR "cpu0_stress: Failed to create thread\n"); return PTR_ERR(stress_task); } // 绑定到 CPU0 kthread_bind(stress_task, 0); // 启动线程 wake_up_process(stress_task); printk(KERN_INFO "cpu0_stress: Module loaded, now stressing CPU0.\n"); return 0; } static void __exit cpu0_stress_exit(void) { if (stress_task) { printk(KERN_INFO "cpu0_stress: Stopping thread...\n"); kthread_stop(stress_task); // 会阻塞直到线程退出 printk(KERN_INFO "cpu0_stress: Thread stopped.\n"); } printk(KERN_INFO "cpu0_stress: Module unloaded.\n"); } module_init(cpu0_stress_init); module_exit(cpu0_stress_exit); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Tester"); MODULE_DESCRIPTION("Stress only CPU0 - for Linux 4.4.115"); MODULE_VERSION("1.0"); 运行后cpu占满了但还是没有丢包情况
最新发布
10-13
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值