如何交错执行两个共享变量进程以输出"x is 7"?
First, let's restate the identical code for both processes clearly:
shared int x; x = 7; while (true) { x = x - 1; x = x + 1; if (x != 7) printf("x is %d", x); }
Normally, if a process runs its loop body sequentially, x will always stay at 7 after the x-1 and x+1 pair—so the if condition never triggers, and nothing gets printed. To get the output "x is 7", we need to exploit the gap between the if (x !=7) check and the subsequent printf call: these are two separate memory operations, so another process can modify x in between them.
Here's a step-by-step interleaving that makes this happen (let's call the processes P1 and P2):
- Both processes finish their initial
x =7assignment (shared memory ensuresxis 7 here). - P1 runs
x = x -1;→xbecomes 6. - P2 runs
x = x -1;→xbecomes 5. - P1 runs
x = x +1;→xbecomes 6. - P1 hits the
if (x !=7)check and readsx→ it reads 6, so the condition is true (6≠7), and proceeds to theprintfstatement. - Before P1 reads
xforprintf, P2 runsx = x +1;→xbecomes 6. - P2 runs
x = x +1;again →xbecomes 7. - P1 finally reads
xfor theprintf→ it reads 7, so the output is "x is 7".
Why This Works
The key is the time between the if condition's read of x and the printf's read of x. Since these are distinct operations, there's a window where the other process can tweak the shared x variable. The if triggers because x wasn't 7 when checked, but by the time printf fetches the value, the other process has restored x to 7.
内容的提问来源于stack exchange,提问作者user9648060

