0

基于以下代码,我需要找到x 的最小和最大最终值

x=1
i=1

cobegin

while (i<4)    while (i<4)
  begin          begin
    x=x*2          x=x*2
    i=i+1          i=i+1 
  end            end

coend

我认为x 可以具有的最小值是 8,如果循环按顺序执行。并且x 可以有的最大值是 16,如果程序先进入其中一个循环,切换到另一个循环并执行它直到 x=8 和 i=4,并完成第一个循环,然后 x=16 和 i= 5. 它是否正确?我是否错过了 x 可能更大或更低的任何情况?

4

3 回答 3

1

你提出的答案是正确的!

于 2013-02-20T19:24:47.280 回答
1

这取决于是否是原子操作(这意味着在获取的值i=i+1和设置之前x=x*2不会发生任何事情)。i

如果不是原子的:

最大值: x = 64

x = 1
i = 1
x = 2 (from 1)
x = 4 (from 2)
i = 2 (from 1+2) // get i=1 for both
x = 8 (from 1)
x = 16 (from 2)
i = 3 (from 1+2) // get i=2 for both
x = 32 (from 1)
x = 64 (from 2)

最小值: x = 4

x = 1
i = 1
x = 2 (from 1+2) // get x=1 for both
i = 2 (from 1)
i = 3 (from 2)
x = 4 (from 1)
i = 4 (from 2)

如果是原子的:

最大值: x = 16

x = 1
i = 1
x = 2 (from 1)
x = 4 (from 2)
i = 2 (from 1)
i = 3 (from 2)
x = 8 (from 1)
x = 16 (from 2)
i = 4 (from 1)
i = 5 (from 2)

最小值: x = 8

x = 1
i = 1
x = 2 (from 1)
x = 4 (from 2)
i = 2 (from 1)
i = 3 (from 2)
x = 8 (from 1)
i = 4 (from 2)
于 2013-02-20T19:27:16.733 回答
1

事实证明,在非原子情况下,最小值为 2,最大值为 512。

对于 x=2:

Process 2 (right loop) executes the [MOV r1, x] assembly instruction of line x=x*2, then switches to Process 1 (left loop). 
Process 1 loops until x=16 and i=4, then it exits.
Back to process 2, which executes [MUL r1, r1], [MOV x,r1], completing the line x=x*2. It then executes i++, yielding i=5, and exits the loop. 
The final value of x is 2.

对于 x=512:

Process 2 executes x=x*2 (x=2) and [MOV r1,i], then switches.
Process 1 loops, yielding (x=4,i=2), (x=8,i=3), (x=16,i=4), then switches.
Process 2 executes [inc r1] and [MOV i,r1]. Now i=2. Process 2 loops and executes x=x*2 (x=32), then [mov r1,i], and switches with i=2.
Process 1 loops, yielding (x=64,i=3), (x=128,i=4), then switches.
Process 2 executes [inc r1] and [MOV i,r1]. Now i=3. Process 2 loops and executes x=x*2 (x=256), then [mov r1,i], and switches.
Process 1 loops, yielding (x=512,i=4), then switches.
Process 2 executes [inc r1] and [MOV i,r1]. Now i=4.
Process 1 and 2 exit. x=512 and i=4.
于 2013-03-15T23:42:02.523 回答