温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2021-08-05 17:09:28 来源:亿速云 阅读:130 作者:Leah 栏目:大数据

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<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)

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

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI