What's the possible result of the following code in concurrency situation?

rickyu

New Member
#1
I have seen an interview question as below: What's the possible range of the result of the following code:
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;
}
The given answer is [50,100]. However, I thought it should be [2,100]. If given sequence as below, sum will be 2.
  1. 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).
  2. thread t2 get the cpu, and increase (49 times), and now the sum will be 49.
  3. thread t1 get the cpu, and compute sum = c1 + 1, now sum is 1.
  4. 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.
  5. 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.
  6. thread t1 get the cpu, and write the cached result c1 to sum, now sum is 2.
    Am I right?
 

Từ khóa phổ biến

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.

Top