千家信息网

C++中怎么利用volatile关键字实现同步处理​

发表于:2025-02-08 作者:千家信息网编辑
千家信息网最后更新 2025年02月08日,C++中怎么利用volatile关键字实现同步处理,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。Reason(原因)In
千家信息网最后更新 2025年02月08日C++中怎么利用volatile关键字实现同步处理​

C++中怎么利用volatile关键字实现同步处理,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

Reason(原因)

In C++, unlike some other languages, volatile does not provide atomicity, does not synchronize between threads, and does not prevent instruction reordering (neither compiler nor hardware). It simply has nothing to do with concurrency.

不像其他语言,在C++中volatile不会保证原子性,不会在线程之间同步,并且不会防止指令重排(无论是编译器还是硬件)。它没有为并发做任何事情。

Example, bad(反面示例):


int free_slots = max_slots; // current source of memory for objects
Pool* use(){ if (int n = free_slots--) return &pool[n];}

Here we have a problem: This is perfectly good code in a single-threaded program, but have two threads execute this and there is a race condition on free_slots so that two threads might get the same value and free_slots. That's (obviously) a bad data race, so people trained in other languages may try to fix it like this:

代码中存在一个问题:在单线程程序中,这是一段完美的代码,但是它会被两个线程执行,在free_slots上会发生数据竞争而导致两个线程可能得到同样的值和free_slots。这(显然)是一个坏的数据竞争,因此被其他语言训练过的人们可能会这样解决这个问题:


volatile int free_slots = max_slots; // current source of memory for objects
Pool* use(){ if (int n = free_slots--) return &pool[n];}

This has no effect on synchronization: The data race is still there!

The C++ mechanism for this is atomic types:

这对同步处理没有任何作用:数据竞争还在!C++实现数据同步的机制atomic类型:


atomic free_slots = max_slots; // current source of memory for objects
Pool* use(){ if (int n = free_slots--) return &pool[n];}

Now the -- operation is atomic, rather than a read-increment-write sequence where another thread might get in-between the individual operations.

现在--操作是原子化的,而不是另一个线程可以插入操作的读-增量-写序列。

Alternative(其他选项)

Use atomic types where you might have used volatile in some other language. Use a mutex for more complicated examples.

如果你曾经在其他语言中使用过volatile关键字,使用原子类型。更复杂的例子可以使用mutex。

See also(参照)

(rare) proper uses of volatile(volatile的正确用法)

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#cp200-use-volatile-only-to-talk-to-non-c-memory)

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注行业资讯频道,感谢您对的支持。

线程 C++ 同步 数据 原子 语言 竞争 关键 关键字 处理 两个 代码 类型 问题 帮助 复杂 清楚 之间 人们 作用 数据库的安全要保护哪些东西 数据库安全各自的含义是什么 生产安全数据库录入 数据库的安全性及管理 数据库安全策略包含哪些 海淀数据库安全审计系统 建立农村房屋安全信息数据库 易用的数据库客户端支持安全管理 连接数据库失败ssl安全错误 数据库的锁怎样保障安全 数据库管理报班费用 spring分布式数据库 数据库系统概论高分笔记 哪里可以学计算机网络技术 阿里云查看服务器地址 与网络安全有关政治的知识 软件开发费与软件费 雀魂服务器没信号 微信两个手机如何导入数据库 聚导航软件开发 阐述目前网络安全的形式 计算机转网络安全 知乎 山西统一软件开发设施厂家现货 方舟生存进化手机版服务器下载 师宗天气预报软件开发 数据库物流公司管理系统设计书 软件开发老师资质有哪些 网络技术应用实验心得 计算机软件开发著作权属于谁 西藏自治区网络安全宣传视频 数据库修改用例 网络安全等保测评文件 网络安全两层含义 香港云服务器怎样保护 湖北新一代网络技术服务保障 腾讯云服务器有固定ip吗 网络安全作业平台下载 专科计算机网络技术课程多吗 软件开发优秀员工事迹材料范文 互联网科技基金哪只好
0