0

我目前正在学习 golang,并且尝试了以下代码:

package main

import (
    "fmt"
)

func main() {
    go routine()
    go routine2()

    fmt.Println("I am not interrupted by Go routine :)")

    for {

    }
}

func routine() {
    for {
        fmt.Println("hello, world!")
    }
}

func routine2() {
    for {
        fmt.Println("hello, world222")
    }
}

当我运行这个程序时,我得到了输出:"hello, world""hello, world222"几秒钟。然而,几秒钟后,我什么也没有得到,但程序仍在运行。

怎么了?为什么程序停止显示hello, worldhello, world222

4

2 回答 2

3

这是因为目前(go 1.10)Go 的调度程序不是抢占式的,也没有计划这样做。

这意味着 Go 的调度程序可能会在一些罕见的情况下卡住,在这种情况下,存在一个无限循环,Go 的调度感觉就像中断一样无所事事。这包括一个空的无限循环。

要阻止 goroutine 进行测试,请使用select{}代替for {}.

参考:

https://github.com/golang/go/issues/11462

https://github.com/golang/go/issues/10958

于 2018-06-18T16:41:15.603 回答
0

您正在使用空for循环烧 CPUselect改用for

import (
    "fmt"
    "time"
)

func main() {
    go routine()
    go routine2()

    fmt.Println("I am not interrupted by Go routine :)")
    select{}
}

func routine() {
    for {
        fmt.Println("hello, world!")
        time.Sleep(time.Second)
    }
}

func routine2() {
    for {
        fmt.Println("hello, world222")
        time.Sleep(time.Second)
    }
}

您的代码没问题,永远不会停止,但它是正确的。

于 2018-06-18T16:41:29.053 回答