使用挥发性只要原子 [英] Using volatile long as an atomic
问题描述
如果我有这样的事情...
If I have something like this...
volatile long something_global = 0;
long some_public_func()
{
return something_global++;
}
难道是合理的当多个线程访问,以期望这code不破(竞争条件)?如果它不是标准的,可以将它仍然可以为关于现代编译一个合理的假设做了什么?
Would it be reasonable to expect this code to not break (race condition) when accessed with multiple threads? If it's not standard, could it still be done as a reasonable assumption about modern compilers?
请注意:所有我使用这个的,是原子递增和递减 - 没有什么票友
NOTE: ALL I'm using this for is atomic increment and decrement - nothing fancier.
推荐答案
没有 - 挥发性并不意味着同步。它只是意味着,每次访问会返回最先进的最新值(而不是在线程本地缓存副本)。
No - volatile does not mean synchronized. It just means that every access will return the most up-to-date value (as opposed to a copy cached locally in the thread).
后递增不是一个原子操作,则存储器访问后跟一个存储器写。交错二者可以意味着该值实际递增一次。
Post-increment is not an atomic operation, it is a memory access followed by a memory write. Interleaving two can mean that the value is actually incremented just once.
这篇关于使用挥发性只要原子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!