【发布时间】:2013-12-19 23:12:31
【问题描述】:
有人告诉我,以下代码示例存在数据竞争条件(当然,假设是多个线程):
class C {
private int x = 0;
private int y = 0;
void f() {
x = 1;
y = 1;
}
void g() {
int a = y;
int b = x;
assert(b >= a);
}
}
然而,我被告知以下“修复”没有数据竞争:
class C {
private int x = 0;
private int y = 0;
void f() {
synchronized(this) { x = 1; }
synchronized(this) { y = 1; }
}
void g() {
int a, b;
synchronized(this) { a = y; }
synchronized(this) { b = x; }
assert(b >= a);
}
}
可以理解,上面的例子还有其他问题,但是我只是想知道为什么第二个代码块没有竞态条件。同步每个赋值语句如何消除数据竞争条件?一次只同步一个赋值语句有什么意义?
澄清一下,数据竞争是这样定义的:
Data races: Simultaneous read/write or write/write of the same
memory location
【问题讨论】:
-
你能解释一下为什么第一个代码有竞争条件吗?
标签: java parallel-processing atomic race-condition