Why Goroutine Can Get Scheduled After Busy Loop?

梦想的初衷 提交于 2020-01-30 04:07:35

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!