liveBook · Manning

Control hazard

As explained in 100 Go Mistakes and How to Avoid Them

A control hazard is an instruction-execution dependency caused by a conditional branch whose outcome determines subsequent instructions.

A control hazard is the dependency created when a conditional branch determines which instructions may execute next. Treating those instructions as freely parallel can produce speculative work that must later be discarded. section 12.3

Conditional execution after an increment

In `s[0]++` followed by `if s[0]%2 == 0 { s[1]++ }`, the branch outcome controls the following increment. A processor may predict the condition from recent history and execute both paths speculatively. If the prediction is wrong, it flushes the execution pipeline, causing a stated penalty of 10 to 20 clock cycles. section 12.3

s[0]++
if s[0]%2 == 0 {
    s[1]++
}

Inspect the compact increment-and-branch sequence that exposes the control dependency. section 12.3

Distinguish the hazard from nearby instruction-level parallelism concerns:

  • Use branch prediction as the processor-level response to control hazards; recognize that incorrect predictions incur pipeline-flush costs. section 12.3
  • Do not confuse control hazards with data hazards, where one instruction needs another instruction's result. section 12.3

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Traces branch prediction, speculative execution, pipeline flushing, and a 10-to-20-cycle penalty, but stops short of hardware implementation details.
Examples
Uses a Go increment-and-conditional-branch loop and hypothetical instructions I2 and I3 to show speculative execution.
What it assumes
Assumes basic instruction execution and conditional branches while introducing instruction-level parallelism and processor hazards.
What you can do after
Evaluate how conditional branches can limit parallel execution and recognize the performance cost of incorrect branch prediction.
How it connects
Connects control hazards with instruction-level parallelism, branch prediction, data hazards, and structural hazards.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Go Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.