Go

What does this print with GOMAXPROCS(1), and why?

Question 151HardGo 1.22 to 1.25
package main

import (
	"fmt"
	"runtime"
	"sync"
)

func main() {
	runtime.GOMAXPROCS(1)
	var wg sync.WaitGroup
	for i := range 5 {
		wg.Add(1)
		go func() {
			defer wg.Done()
			fmt.Print(i, " ")
		}()
	}
	wg.Wait()
}

It usually prints 4 0 1 2 3. When a new goroutine is created, it goes into the P's runnext slot and pushes the previous occupant to the tail of the local queue. After the loop, runnext holds goroutine 4 and the queue holds 0–3. When main blocks in Wait, the scheduler runs runnext first.

Since Go 1.22, each loop iteration has its own i, so every goroutine prints a different value. (range 5 over an integer itself needs Go 1.22. With a classic for i := 0; i < 5; i++ loop under an older go directive, all five goroutines share one i and would all print 5.)

What the interviewer wants to hear: this order is an implementation detail and is not guaranteed. Race builds and future scheduler changes can alter it. If you need an order, enforce it with synchronization.

More on Goroutines & the Scheduler

All 35 Goroutines & the Scheduler questions