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

面向对象思考

共 2170字,需浏览 5分钟

 ·

2020-06-29 23:45

bb4967bf63639a3378739ba3790b315d.webp

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(反面示例):

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)


原文链接

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




觉得本文有帮助?请分享给更多人。

关注微信公众号【面向对象思考】轻松学习每一天!

面向对象开发,面向对象思考!


浏览 28
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报