if (x == 5) // The "Check"{y = x * 2; // The "Act"
// If another thread changed x in between "if (x == 5)" and "y = x * 2" above,// y will not be equal to 10.}
Thread 1: reads x, value is 7Thread 1: add 1 to x, value is now 8Thread 2: reads x, value is 7Thread 1: stores 8 in xThread 2: adds 1 to x, value is now 8Thread 2: stores 8 in x
可以通过在访问共享资源的代码之前使用某种锁定机制来避免竞争条件:
for ( int i = 0; i < 10000000; i++ ){//lock xx = x + 1;//unlock x}