并发线程运行和输出变量
thread concurrently running and output variables
我运行进入一个具有挑战性的Trace这个例子:
假设我们有两个线程并发运行这两个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 的序列(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
我运行进入一个具有挑战性的Trace这个例子:
假设我们有两个线程并发运行这两个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 的序列(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