Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

171. 下面代码有什么问题,请说明? #11

Open
imfuxiao opened this issue Mar 5, 2021 · 0 comments
Open

171. 下面代码有什么问题,请说明? #11

imfuxiao opened this issue Mar 5, 2021 · 0 comments

Comments

@imfuxiao
Copy link

imfuxiao commented Mar 5, 2021

func main() {
    runtime.GOMAXPROCS(1)

    go func() {
        for i:=0;i<10 ;i++  {
            fmt.Println(i)
        }
    }()

    for {}
}

以上代码在go1.14版本之前(不含1.14版本): for {} 独占 CPU 资源导致其他 Goroutine 饿死

这是因为1.14版本之前(不含1.14版本)goroutine抢占式调度设计是在函数调用间隙判断是否可以被抢占, 而for{}内没有函数调用, 所以无法被抢占. 所以导致其他goroutine饿死.

image

在go1.14版本之后(包含go1.14): ** 会打印0123456789, 并且主程会进入死循环**.

这是因为1.14版本(含1.14版本)之后goroutine抢占式调度设计改为基于信号的抢占式调度. 当调度器监控发现某个goroutine执行时间过长且有别的goroutine在等待时, 会把执行时间过长的goroutine暂停, 转而调度等待的goroutine. 所以for循环的goroutine得以执行.

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant