I have seen an interview question as below: What's the possible range of the result of the following code:
The given answer is [50,100]. However, I thought it should be [2,100]. If given sequence as below, sum will be 2.
Mã:
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;
}
- thread t1 get the cpu, and load the initial sum=0 into cache (let's say the cached sum is c1, its value is 0 now).
- thread t2 get the cpu, and increase (49 times), and now the sum will be 49.
- thread t1 get the cpu, and compute sum = c1 + 1, now sum is 1.
- thread t2 get the cpu, and load the sum (=1) and compute sum + 1 and cached the result (c1 is 2 now). Before the c1 is written to variable sum by t1, t2 preempt the cpu.
- thread t2 get the cpu, and increase (1 times) [and now the sum will be x (the value does't matter)], then thread t2 finished.
- thread t1 get the cpu, and write the cached result c1 to sum, now sum is 2.
Am I right?