liveBook · Manning

False sharing

As explained in 100 Go Mistakes and How to Avoid Them

False sharing is a performance problem in which independent variables occupy the same cache line, causing updates by different cores to invalidate one another's cached data.

False sharing is a performance mistake: independent variables share a cache line, so updates from different cores repeatedly invalidate each other's cached data. The code can be race-free yet unexpectedly slow. section 12.2 section 12.11

func count(inputs []Input) Result {
    wg := sync.WaitGroup{}
    wg.Add(2)
 
    result := Result{}                        #1
 
    go func() {
        for i := 0; i < len(inputs); i++ {
            result.sumA += inputs[i].a        #2
        }
        wg.Done()
    }()
 
    go func() {
        for i := 0; i < len(inputs); i++ {
            result.sumB += inputs[i].b        #3
        }
        wg.Done()
    }()
 
    wg.Wait()
    return result
}

Two goroutines independently accumulate sumA and sumB in one Result. Although each goroutine owns its variable, the adjacent fields can occupy the same memory block. section 12.2

A CPU usually copies memory in 64-byte cache lines rather than individual words. L1 data caches are specific to physical cores, so each core may hold a copy of the line containing both fields. Updating one field then invalidates the other core's copy, even though the goroutines never share a variable. section 12.11 section 12.2

type Result struct {
    sumA int64
    _    [56]byte     #1
    sumB int64
}

Padding places sumA and sumB in different memory blocks, reducing cache-line interference when separate cores update them concurrently. section 12.2

Use padding when independent, frequently updated fields run concurrently and profiling shows this bottleneck. Otherwise, preserve the simpler layout; false sharing is a performance issue, not a data-race diagnosis. section 12.2 section 12.11

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Explains memory blocks, 64-byte cache lines, per-core L1D caches, invalidation, and padding, but stops short of benchmark results.
Examples
Demonstrates adjacent sumA and sumB accumulators, two updating goroutines, cache-line replication, and a padded Result struct.
What it assumes
Assumes basic Go concurrency and introduces cache lines, per-core caches, cache coherency, and the distinction from data races.
What you can do after
Diagnose false sharing in concurrent updates and apply struct padding when independent fields contend through shared cache lines.
How it connects
Connects CPU caching, cache lines, cache coherency, concurrency, goroutines, data races, and spatial locality.

Also explained in

Compare how 2 books explain false sharing →

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.