顺序一致性和原子性之间有什么区别? [英] What is the difference between sequential consistency and atomicity?
问题描述
我读到java volatile是顺序一致的,但不是原子的. 对于原子性,java提供了不同的库.
I read that java volatile are sequential consistent but not atomic. For atomicity java provides different library.
有人能用简单的英语解释两者之间的区别吗?
Can someone explain difference between two, in simple english ?
(我认为问题范围包括C/C ++,因此添加了这些语言标签以吸引更大的受众.)
(I believe the question scope includes C/C++ and hence adding those language tags to get bigger audience.)
推荐答案
想象一下类中的这两个变量:
Imagine those two variables in a class:
int i = 0;
volatile int v = 0;
那两种方法
void write() {
i = 5;
v = 2;
}
void read() {
if (v == 2) { System.out.println(i); }
}
易失性语义保证read
不会打印5或什么都不打印(假设没有其他方法在修改字段).如果v
不稳定,则read
可能也会打印0,因为i = 5
和v = 2
可能已重新排序.我想这就是顺序一致性的意思,它具有更广泛的含义.
The volatile semantics guarantee that read
will either print 5 or nothing (assuming no other methods are modifying the fields of course). If v
were not volatile, read
might as well print 0 because i = 5
and v = 2
could have been reordered. I guess that's what you mean by sequential consistency, which has a broader meaning.
另一方面,挥发物不能保证原子性.因此,如果两个线程同时调用此方法(v是相同的volatile int
):
On the other hand, volatile does not guarantee atomicity. So if two threads call this method concurrently (v is the same volatile int
):
void increment() {
v++;
}
您不能保证v会增加2.这是因为v++
实际上是三个语句:
you have no guarantee that v will be incremented by 2. This is because v++
is actually three statements:
load v;
increment v;
store v;
并且由于线程交织,v只能增加一次(两个线程将加载相同的值).
and because of thread interleaving v could only be incremented once (both thread will load the same value).
这篇关于顺序一致性和原子性之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!