9

Java volatile は順次一貫性がありますが、アトミックではないことを読みました。原子性のために、Java は異なるライブラリを提供します。

誰かが簡単な英語で2つの違いを説明できますか?

(質問の範囲には C/C++ が含まれているため、これらの言語タグを追加してより多くの聴衆を獲得できると思います。)

4

2 に答える 2

8

クラス内のこれら 2 つの変数を想像してください。

int i = 0;
volatile int v = 0;

そして、それらの2つの方法

void write() {
    i = 5;
    v = 2;
}

void read() {
    if (v == 2) { System.out.println(i); }
}

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.

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++;
}

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;

and because of thread interleaving v could only be incremented once (both thread will load the same value).

于 2013-03-17T22:33:04.200 に答える
6

次の 2 つの変数があるとします。

public int a = 0;
public volatile int b = 0;

そして、1つのスレッドがそうするとします

a = 1;
b = 2;

別のスレッドがこれらの値を読み取り、b == 2 を確認した場合、a == 1 も確認されることが保証されます。

ただし、2 つの書き込みはアトミック操作の一部ではないため、読み取りスレッドはa == 1とを見ることができます。そのため、最初のスレッドが に値を割り当てる前に、読み取りスレッドは に加えられた変更を見る可能性があります。b == 0ab

これら 2 つの書き込みをアトミックにするには、これら 2 つの変数へのアクセスを同期する必要があります。

synchronized (lock) {
    a = 1;
    b = 2;
}

...

synchronized (lock) {
    System.out.println("a = " + a + "; b = " + b);
}

この場合、読み取りスレッドはa == 0and b == 0、またはa == 1andを参照しますがb == 2、中間状態は決して参照しません。

于 2013-03-17T22:32:31.207 に答える