Skip to content

Instantly share code, notes, and snippets.

@itczl22
Created December 14, 2019 16:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save itczl22/af0e3794ba51bbac4d71e00e38f9e641 to your computer and use it in GitHub Desktop.
Save itczl22/af0e3794ba51bbac4d71e00e38f9e641 to your computer and use it in GitHub Desktop.
go scheduler陷阱
func main() {
var x int
threads := runtime.GOMAXPROCS(0)
for i := 0; i < threads; i++ {
go func() {
for { x++ }
}()
}
time.Sleep(time.Second)
fmt.Println("x =", x)
}
// 程序会进入死循环,不会输出最后一行
// 这和goroutine的调度有关, go是协作式而非抢占式调度
// go的调度时机是:使用go关键字、GC、系统调用、内存同步访问(如atomic、mutex、channel)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment