前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则CP.8:不要使用volatile关键字实现同步处理​

C++核心准则CP.8:不要使用volatile关键字实现同步处理​

作者头像
面向对象思考
发布2020-07-03 17:07:38
3410
发布2020-07-03 17:07:38
举报

CP.8: Don't try to use volatile for synchronization

CP.8:不要使用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(反面示例):

代码语言:javascript
复制
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。这(显然)是一个坏的数据竞争,因此被其他语言训练过的人们可能会这样解决这个问题:

代码语言:javascript
复制
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类型:

代码语言:javascript
复制
atomic<int> 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)

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#cp8-dont-try-to-use-volatile-for-synchronization

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-06-29,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Reason(原因)
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档