Kacam.net

Computer systems

重排序,是编译器干的还是 CPU 干的

你说的重排序,是编译器干的还是 CPU 干的?

Copy the prompt, then pick a model. It plays the interviewer and asks you through it scene by scene instead of handing you the answer.

On a phone with the app installed, the system opens the app directly. Links cannot open external apps inside WeChat — open it in a browser first.

The copied text ends with the answer key the model grades you against. Don't read it yourself first — working it out on your own is the point.

这一份从一段十行的代码开始:两个线程,一个写、一个读,问你会不会读到旧值。答「不会」和答「会」都要接着回答同一个问题 —— 谁把顺序换了。

目标是把「重排序」拆成三层:编译器、CPU 乱序、写缓冲与缓存可见性。三层都保证单线程看起来没变,所以这类 bug 在本地永远复现不了。

还有一问是照妖镜:你说的 volatile,能保证 i++ 是原子的吗?以及 C 的 volatile 和 Java 的 volatile 是不是同一回事。

★★★★★ · about 40 min · Tests: 三层重排序、可见性 vs 有序性 vs 原子性、x86 为什么骗了你

What this one drills

Reordering and visibility Caches and cache lines

Have you done this one?

Sign in to mark this one as practised — next time you come back you'll see when you did it.

Notes from people who did this one

Nobody has written yet. After you run it, say what came out of the conversation — which scene stumped you, which conclusion you changed afterwards.

Sign in to write a note.

How to use this

This set teaches rather than interrogates: it guides you instead of pressing until you have nothing left to say. When you're stuck it first asks which layer you're stuck at (never heard of it / know it but not why / know why but can't apply it), then decides what to give. Only after guiding you twice on the same point will it spell it out — and then it asks you to say it back in your own words.

It will keep pushing you for numbers: answer "there's some overhead" or "it's faster" and it cuts you off. A conclusion you can't put a number on is a memorised one — that's exactly what this set drills.

How to start

  1. Pick one, open it, copy the prompt.
  2. Paste it into a brand-new conversation, say nothing, and wait for its first question.
  3. Expect to be asked for orders of magnitude: how many nanoseconds, how many microseconds, how many times slower. Saying you don't know is fine — it notes it and moves on.

Four commands you can call out at any time

  • 跳过 move to the next scene now
  • 换个说法 explain this bit again from another angle
  • 直说吧 spell the answer out, then make me say it back
  • 复盘 jump to the wrap-up and print the review card

Three traps

  • Don't read the answer key at the end first — that "how people get it wrong" section is the answer to every question it will ask.
  • Don't reach for the jargon. Saying "that's a TLB miss" is easy; saying how much cheaper it is than a page fault is the part that counts.
  • When it starts praising you, point it back to the "don't praise me" rule. Guiding is not coddling.

Want a feel for the numbers? Start with random reads and the first-byte one. For production debugging: malloc, TCP stalls, context switches. Writing concurrent code: reordering and false sharing.