问题
See these code below. I am not doing this in any production, just for studying purpose.
I have heard from many posters that busy loop usually prevents from scheduling because they leave no chance for the go sheduler to scheduler. If this is true why deadloop() goroutine can gets scheduled??
I am using golang 1.12
and testing on windows os.
func main() {
go deadloop() // v1 -- keeps printing forever
var i =1
for {
i++
}
}
func deadloop() {
i := 0
for {
fmt.Printf("from deadloop\n")
i++
}
}
update: I was confused so that I didn't say it in a clearer way for the problem. I change the contents today, but I still have same question.
回答1:
As per @Cerise's answer, it's because the busy loop, the for
loop inside your main
function. If the purpose of the loop is to prevent main
of exiting then don't use for
, use select
instead. See code below:
func main() {
go deadloop2()
select { } // <----- here
}
func deadloop2() {
i := 0
for {
fmt.Printf("from deadloop i=%d\n", i)
i++
}
}
来源:https://stackoverflow.com/questions/57193098/why-goroutine-can-get-scheduled-after-busy-loop