You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何交错执行两个共享变量进程以输出"x is 7"?

How to Get "x is 7" Output from Interleaving These Two Processes

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):

  1. Both processes finish their initial x =7 assignment (shared memory ensures x is 7 here).
  2. P1 runs x = x -1; → x becomes 6.
  3. P2 runs x = x -1; → x becomes 5.
  4. P1 runs x = x +1; → x becomes 6.
  5. P1 hits the if (x !=7) check and reads x → it reads 6, so the condition is true (6≠7), and proceeds to the printf statement.
  6. Before P1 reads x for printf, P2 runs x = x +1; → x becomes 6.
  7. P2 runs x = x +1; again → x becomes 7.
  8. P1 finally reads x for the printf → 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 03:54:31