vs2012 c语言 创建线程,c – 在VS2012中使用’volatile’关键字的最佳实践

博客讨论了在将开发环境从 VS2008 升级到 VS2012 后,C++ 中 volatile 关键字的含义变化。微软文档指出,C++11 标准中的 volatile 关键字仅用于硬件访问,而不应用于线程间通信,推荐使用 std::atomic。文章作者提出是否应删除 volatile 并替换为 C11 标准等效物,以及不这样做的潜在风险。作者正在进行大规模重构,并寻求建议。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

自从我们的开发和构建环境从VS2008升级到VS2012以来,我对在我们的遗留代码库中使用volatile关键字的含义感到困惑(它非常广泛,因为从“旧”时代管理线程有很多复制模式).

Microsoft在VS2012文档中有以下评论:

If you are familiar with the C# volatile keyword,or familiar with the behavior of volatile in earlier versions of Visual C++,be aware that the C++11 ISO Standard volatile keyword is different and is supported in Visual Studio when the /volatile:iso compiler option is specified. (For ARM,it’s specified by default). The volatile keyword in C++11 ISO Standard code is to be used only for hardware access; do not use it for inter-thread communication. For inter-thread communication,use mechanisms such as std::atomic from the C++ Standard Template Library.

它继续说:

When the /volatile:ms compiler option is used—by default when architectures other than ARM are targeted—the compiler generates extra code to maintain ordering among references to volatile objects in addition to maintaining ordering to references to other global objects.

我认为这意味着我们现有的代码不会破坏,但不一定是可移植的(对我们来说不是问题).

但是,如果可能的话,它确实提出了这些问题,我希望得到一些建议:

>我们是否应该在我们的代码中删除volatile限定符的使用并替换为符合C 11 ISO标准的等价物,即使我们不会将代码从MS中移除?

>如果我们不这样做,是否有任何缺点?

我理解这不是一个特定的编程问题,但我们正在进行一些非常重要的重构,我希望能够为这项工作提供一些明智的指导.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值