5 ms·
Go's memory model [pdf]
- karmakaze 8y agoI was hoping that there were answers here. Instead I got: Go Memory Model Two purposes: ● Make guarantees for programmers. ● Allow compilers/hardware to make certain changes to programs. Ideally, perfectly balanced. In practice, more conservative: might do neither. Explicit concern: Leave room for future refinement, refraining from: ● making debatable guarantees to programmers ● allowing compilers/hardware to make debatable changes to programs and specifically I was curious about sync/atomic and only got a proposal (which ironically says 'be like Java'): Package sync/atomic is conspicuously missing. Proposal: match Java volatile and C++ memory_order_seq_cst. ● An atomic write happens before an atomic read that observes the write. ● The outcome of atomic operations must be consistent with a total order over all atomic operations in the program. TL;DR Go Memory Model Semantics based on happens-before: ● If p imports q, q’s init happens before p’s. ● Package main’s init happens before main.main ● The go statement happens before the created goroutine’s execution ● A send (or close) on a channel happens before the receive ● Unlock happens before subsequent Lock A read r is allowed to observe a write w to location v if: ● r does not happen before w ● There is no write w’ to v such that w < w’ < r. [< is happens-before] A read r is therefore guaranteed to observe w if: ● w happens before r (w < r) ● For any other write w’ to v, w’ < w or r < w’ Intent: like DRF-SC without allowing compilers to ruin programmers’ lives. Note: DRF-SC Data Race Free-Sequentially Consistent