当前位置: 首页 > news >正文

linux kernel synchronization 2

Per CPU Variables

  • A CPU should not access the elements of the array corresponding to other CPU.
  • 每个CPU拥有该变量的独立副本
  • 无需加锁 - 由于每个CPU只操作自己的副本,因此读写自己的副本时不会产生竞争条件
  • 缓存优化 - 每个数据结构在主存中对齐,确保每个数据结构落在硬件缓存的不同行,提高缓存命中率
点击查看代码
// 获取当前CPU ID并禁用抢占
int cpu = get_cpu(); 
// 在这里执行需要在当前CPU上运行的代码
// 重新启用抢占
put_cpu();#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/percpu.h>MODULE_LICENSE("GPL");//定义per cpu 变量
DEFINE_PER_CPU(int, counter);static int __init test_hello_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); //获取per cpu counter变量pr_info("Value of counter is %d at Processor:%d\n", value, i);}get_cpu_var(counter) = 10; //获取per cpu counter变量pr_info("Printing counter value of all processor after updating current processor:%d\n",smp_processor_id());put_cpu_var(counter);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 -1;
}static void __exit test_hello_exit(void)
{pr_info("%s: In exit\n", __func__);
}module_init(test_hello_init);
module_exit(test_hello_exit);

Dynamically allocated per-CPU variables

点击查看代码
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/percpu.h>MODULE_LICENSE("GPL");static int *dynamic_counter;static int __init test_hello_init(void)
{int cpu = get_cpu();int i;dynamic_counter = alloc_percpu(int);pr_info("cpu:%d\n", cpu);*per_cpu_ptr(dynamic_counter, cpu) = 1000;put_cpu();for (i = 0; i < num_online_cpus(); i++)pr_info("cpu:%d\tcounter:%d\n",i, *per_cpu_ptr(dynamic_counter, i));free_percpu(dynamic_counter);return -1;
}static void __exit test_hello_exit(void)
{pr_info("%s: In exit\n", __func__);
}module_init(test_hello_init);
module_exit(test_hello_exit);
只能保护多个cpu并发
http://www.hskmm.com/?act=detail&tid=11106

相关文章:

  • MySQL高阶查询语句与视图实战指南 - 指南
  • 订单未支付多种方案
  • 架构风格
  • Twincat 中如何将位变量链接到字节
  • 不管不管,就要你的特殊对待(权限)
  • 202003_攻防世界_功夫再高也怕菜刀
  • 工业软件:重塑协同流程、降低制造成本的关键器具
  • 实用指南:【2025最新版】PCL点云处理算法汇总(C++长期更新版)
  • Gemini Proxy for Xcode 26
  • 数据类型拓展
  • 类型转换
  • 本地布署Qwen-Image全量蒸馏加速模型 - yi
  • Android常用ADB命令
  • 【2025PolarCTF秋季个人赛】WEB方向部分wp
  • 人工智能大模型 基础知识汇总
  • 2025 CCPC 江西省赛 南昌邀请赛 ABCDEGHKL
  • 小米手机刷机+root权限
  • Android Studio无线调试手表App
  • Minimind-一个开源LLM项目的代码分析1:模型结构
  • JavaDay8
  • basic - segment tree
  • 势能分析揭开一些算法的秘密
  • 企业省钱又安全的5款Linux发行版:从Ubuntu到Pop!_OS全面解析
  • how to count
  • 第六章 数组
  • basic - graph theory
  • 详细介绍:阻塞 IO为什么叫BIO,非阻塞IO为什么叫NIO,异步IO为什么叫AIO
  • Ubuntu系统使用gcc和Makefile编译C程序
  • 构造选记
  • 0133_解释器模式(Interpreter)