Distinguish specification and implementation
Distinguish specification and implementation
A goroutine is a concurrent execution of a function. The language and memory model define ordering through synchronization, not which goroutine runs next. Scheduler queues, thread assignment and preemption heuristics belong to the runtime implementation and can change. Build correctness using channels, locks or other documented synchronization rather than observed scheduling order.
package main
import ( "fmt" "sort")
func main() { out := make(chan string, 2) go func() { out <- "A" }() go func() { out <- "B" }() v := []string{<-out, <-out} sort.Strings(v) fmt.Println(v)}Two sends can arrive in either order. Sorting makes the output deterministic without imposing an execution order. Repeating the example cannot prove that one order is impossible. A single observed order is not a contract.
Expected output:
[A B]Enforce a dependency explicitly
package main
import ( "fmt")
func main() { ready := make(chan struct{}) done := make(chan struct{}) go func() { fmt.Println("prepare"); close(ready) }() go func() { <-ready; fmt.Println("consume"); close(done) }() <-done}Closing ready synchronizes with a receive observing that closure. The second print follows the first without a sleep or assumptions about scheduling. A goroutine returning alone does not establish such an ordering with another goroutine.
Expected output:
prepareconsumeTry it locally
Launch two workers computing 4 and 9; collect both values and print their sum without depending on arrival order.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Runtime scheduler 01: Distinguish specification and implementation
Check the lesson objective before moving on.
What determines which runnable goroutine executes first?
What establishes the prepare-before-consume dependency?