当前位置: 首页 > 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.gsyq.cn/news/8744.html

相关文章:

  • MySQL高阶查询语句与视图实战指南 - 指南
  • 订单未支付多种方案
  • Twincat 中如何将位变量链接到字节
  • 实用指南:【2025最新版】PCL点云处理算法汇总(C++长期更新版)
  • Gemini Proxy for Xcode 26
  • 网络分析模型五
  • Android常用ADB命令
  • 【2025PolarCTF秋季个人赛】WEB方向部分wp
  • 电池热失控(Thermal Runaway of the Battery) - 详解
  • 人工智能大模型 基础知识汇总
  • JavaDay8
  • how to count
  • Ubuntu系统使用gcc和Makefile编译C程序
  • 构造选记
  • 碎碎念(十七)
  • 在 macOS 上准备 CentOS 7.5 离线迁移文件的完整指南
  • 配置Spring框架以连接SQL Server数据库
  • 这一辈子大多数日子是无聊的
  • Elasticsearch面试精讲 Day 11:索引模板与动态映射 - 指南
  • Go 实现验证码识别
  • 跳出 AI 编程的「兔子洞」,4 个实战策略帮你解决90%的死循环
  • 暗黑破坏神4 任务-坚守传统-向古老的雕像展示你坚守的传统
  • C++编程软件 Dev-C++ 安装及使用流程
  • DLL植入漏洞分类与微软安全响应指南
  • 市场交易反心理特征之二:忽视热点切换的苗头
  • 贪心算法应用:投资组合再平衡问题详解 - 实践
  • MCP:Trae中集成Playwright 实现网页自动化测试
  • C语言中的字符、字符串及内存操作函数详细讲解
  • 06、訊息收集
  • 精选 4 款基于 .NET 开源、功能强大的 Windows 系统优化工具,助力轻松提升 Windows 系统性能与使用体验!