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
t1get the cpu, and load the initialsum=0into cache (let's say the cached sum isc1, its value is0now). - thread
t2get the cpu, and increase (49 times), and now the sum will be 49. - thread
t1get the cpu, and computesum = c1 + 1, nowsumis1. - thread
t2get the cpu, and load thesum(=1) and computesum + 1and cached the result (c1is2now). Before thec1is written to variablesumbyt1,t2preempt the cpu. - thread
t2get the cpu, and increase (1 times) [and now thesumwill bex(the value does't matter)], thenthread t2finished. thread
t1get the cpu, and write the cached resultc1to sum, nowsumis2.Am I right?