|
| 1 | +package main |
| 2 | + |
| 3 | +// Large struct that spans multiple cache lines (64 bytes each) |
| 4 | +type LargeStruct struct { |
| 5 | + A uint64 // 0-7 (cache line 0) |
| 6 | + B uint64 // 8-15 (cache line 0) |
| 7 | + C uint64 // 16-23 (cache line 0) |
| 8 | + D uint64 // 24-31 (cache line 0) |
| 9 | + E uint64 // 32-39 (cache line 0) |
| 10 | + F uint64 // 40-47 (cache line 0) |
| 11 | + G uint64 // 48-55 (cache line 0) |
| 12 | + H uint64 // 56-63 (cache line 0) - exactly fills line 0 |
| 13 | + I uint64 // 64-71 (cache line 1) |
| 14 | + J uint64 // 72-79 (cache line 1) |
| 15 | +} |
| 16 | + |
| 17 | +// Struct with a field that crosses cache line boundary |
| 18 | +type CacheLineCrosser struct { |
| 19 | + Padding [60]byte // 0-59 (cache line 0) |
| 20 | + Big [16]byte // 60-75 - CROSSES cache line 0→1! |
| 21 | + After uint64 // 80-87 (cache line 1) |
| 22 | +} |
| 23 | + |
| 24 | +// False sharing example - commonly accessed together but on different lines |
| 25 | +type FalseSharingRisk struct { |
| 26 | + Counter1 uint64 // 0-7 (cache line 0) - hot field |
| 27 | + Padding [56]byte // 8-63 (fills cache line 0) |
| 28 | + Counter2 uint64 // 64-71 (cache line 1) - hot field |
| 29 | +} |
| 30 | + |
| 31 | +// Well-aligned for concurrent access |
| 32 | +type CacheAligned struct { |
| 33 | + Counter1 uint64 // cache line 0 |
| 34 | + _pad1 [56]byte // explicit padding to fill line |
| 35 | + Counter2 uint64 // cache line 1 |
| 36 | + _pad2 [56]byte // explicit padding to fill line |
| 37 | +} |
| 38 | + |
| 39 | +// Typical struct that may cross cache lines unintentionally |
| 40 | +type HTTPRequest struct { |
| 41 | + Method string // 0-15 (16 bytes) |
| 42 | + URL string // 16-31 (16 bytes) |
| 43 | + Headers []byte // 32-55 (24 bytes slice header) |
| 44 | + Body []byte // 56-79 - CROSSES cache line! |
| 45 | + ContentLen int64 // 80-87 |
| 46 | + StatusCode int32 // 88-91 |
| 47 | + IsSecure bool // 92 |
| 48 | + KeepAlive bool // 93 |
| 49 | +} |
0 commit comments