Created
December 14, 2019 16:04
-
-
Save itczl22/af0e3794ba51bbac4d71e00e38f9e641 to your computer and use it in GitHub Desktop.
go scheduler陷阱
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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