扬帆大鱼
改变状态,runtime.GOMAXPROCS(1)假设,将失败;即使只有两个 go-routines:func main() { runtime.GOMAXPROCS(1) start := make(chan struct{}) wg := &sync.WaitGroup{} N := 2 //10, 1000, 10000, ... fails with even 2 go-routines for i := 0; i < N; i++ { wg.Add(1) go func() { defer wg.Done() <-start //processing state initialState := globalState //give another goroutine a chance, by halting this one //and lend some processing cycles //(also simulating "concurrent" processing of initialState) runtime.Gosched() if globalState != initialState { panic(fmt.Sprintf("oops! %d != %d", initialState, globalState)) } globalState = initialState + 1 }() } close(start) wg.Wait() log.Println(`global state:`, globalState)}var ( globalState int)其他答案更详细 - 有利于研究并发编程的不同方面。