I have seen an interview question as below: What's the possible range of the result of the following code:
void ThreadProc(int& sum)
{
for (int i = 1; i <= 50; i++)
{
sum += 1;
}
}
int main()
{
int sum = 0;
thread t1(ThreadProc, std::ref(sum));
thread t2(ThreadProc, std::ref(sum));
t1.join();
t2.join();
cout << sum << '\n';
return 0;
}
The given answer is [50,100].
However, I thought it should be [2,100].
If given sequence as below, sum
will be 2.
- thread
t1
get the cpu, and load the initialsum=0
into cache (let's say the cached sum isc1
, its value is0
now). - thread
t2
get the cpu, and increase (49 times), and now the sum will be 49. - thread
t1
get the cpu, and computesum = c1 + 1
, nowsum
is1
. - thread
t2
get the cpu, and load thesum
(=1
) and computesum + 1
and cached the result (c1
is2
now). Before thec1
is written to variablesum
byt1
,t2
preempt the cpu. - thread
t2
get the cpu, and increase (1 times) [and now thesum
will bex
(the value does't matter)], thenthread t2
finished. thread
t1
get the cpu, and write the cached resultc1
to sum, nowsum
is2
.Am I right?