C++中怎么利用volatile关键字实现同步处理
C++中怎么利用volatile关键字实现同步处理,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。
10年积累的成都做网站、网站建设经验,可以快速应对客户对网站的新想法和需求。提供各种问题对应的解决方案。让选择我们的客户得到更好、更有力的网络服务。我虽然不认识你,你也不认识我。但先做网站后付款的网站建设流程,更有海兴免费网站建设让你可以放心的选择与我们合作。
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++中怎么利用volatile关键字实现同步处理
分享地址:http://pwwzsj.com/article/pehggi.html