线程并发运行和输出变量

时间:2015-02-26 17:00:21

标签: c++ multithreading concurrency race-condition critical-section

我遇到了一个挑战跟踪这个例子: 假设我们有两个线程同时运行这两个threads。在以下代码中,所有线程都访问共享变量a, b, c。运行此代码后c的预期值为:4,7,6,13,-3,14,1.

任何有关此输出的帮助或想法?

Initialization 
a=4;
b=0;
c=0;

Thread 1
if (a<b) then
    c=b-a;
else
    c=b+a;
endif

Thread 2
b=10;
c=-3;

1 个答案:

答案 0 :(得分:0)

1的序列(c = b + a实现为c = b,c + = a):

    (a<b) false  // thread 1 a == 4, b == 0
    else         // thread 1
    c = b + ...  // thread 1 c = b == 0
    b = 10       // thread 2
    c = -3       // thread 2 c = -3
    c = ... + a  // thread 1 c += a == 1

4

的序列
   (a<b) false   // thread 1 a == 4, b == 0
   a + b         // thread 1 sum of 4 + 0 = 4
   b = 10        // thread 2
   c = -3        // thread 2
   c = a + b     // thread 1  c = previously calculated sum of 4

-3

的序列
   ...           // thread 1 runs first
   c = -3        // thread 2, last statement

13

的序列
   ...           // thread 1 is going to calculate c = a, c = b - c
   c = 4         // thread 1 c = a
   b = 10        // thread 2
   c = -3        // thread 2
   c = b - c     // thread 1 c = 10 - (-3) = 13

6

的序列
   b = 10        // thread 2
   c = -3        // thread 2
   (a<b) true    // thread 1
   c = b-a       // thread 1  c = 10 - 4 = 6

14

的序列
   (a<b) false   // thread 1
   b = 10        // thread 2
   c = -3        // thread 2
   c = b+a       // thread 1  c = 10 + 4 = 14

7的序列(c = b + a实现为c = a,c + = b):

   (a<b) true    // thread 1
   c = a         // thread 1  c = 4
   b = 10        // thread 2
   c = -3        // thread 2
   c += b        // thread 1  c = -3 + 10 = 7