问题描述
朋友之间的赌博。
sum变量定义为全局变量。
,我们有两个线程运行在1..100循环,每个循环增加1。
Betting between friends.sum variable is defined as global.and we have 2 threads that run over loop 1..100 and increments sum by 1 every loop.
将打印什么?
sum =?
what will be printed?"sum="?
int sum = 0;
void func(){
for (int i=0 ; i<= 100; i++){
sum++;
}
}
int main(){
t1 = Thread(func);
t2 = Thread(func);
t1.start();
t2.start();
t1.join();
t2.join();
cout << "sum = " << sum;
return 0;
}
推荐答案
没有单一值的和。如果有0个竞争条件,值将为200.如果在循环的每次迭代中都有竞争条件(不太可能),它可以低至100.或者它可以在之间的任何地方。
There is no single value for sum. If there are 0 race conditions, the value will be 200. If there are race conditions on every iteration of the loop (unlikely) it could be as low as 100. Or it could be anywhere in between.
你可能认为sum ++是一个原子操作,但它实际上是sum = sum + 1的语法糖。在这个操作中有一个竞争条件的可能性,所以sum每次都可能不同你运行它。
You probably think of sum++ as an atomic operation, but it is actually syntactic sugar for sum = sum + 1. There is the possibility of a race condition within this operation, so sum could be different every time you run it.
想象sum的当前值是10.然后t1进入循环并读取sum(10)的值,然后停止让t2开始运行。 t2将读取与t1相同的值(10)。然后当每个线程递增时,它们都将递增它到11.如果没有其他竞争条件,sum的结束值将为199.
Imagine the current value of sum is 10. Then t1 gets into the loop and reads the value of sum (10), and then is stopped to let t2 begin running. t2 will then reads the same value (10) of sum as t1. Then when each thread increments they will both increment it to 11. If there are no other race conditions the end value of sum would be 199.
这是更糟的情况。想象一下sum的当前值再次是10。 t1进入循环并读取sum(10)的值,然后停止以使t2开始运行。 t2,再次读取sum(10)的值,然后停止它自身。现在t1再次开始运行,它循环10次,将sum的值设置为20.现在t2再次启动并将sum增加到11,所以你实际上减去了sum的值。
Here's an even worse case. Imagine the current value of sum is 10 again. t1 gets into the loop and reads the value of sum (10), then is stopped to let t2 begin running. t2, again, reads the value of sum (10) and then itself is stopped. Now t1 begins running again and it loops through 10 times setting the value of sum to 20. Now t2 starts up again and increments sum to 11, so you've actually decremented the value of sum.
这篇关于运算符++(前缀)与线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!