duanfen2008 2018-06-18 16:34
浏览 363
已采纳

Goroutine执行几秒钟但停止[重复]

I'm currently learning golang and I've tried the following code:

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")
    }
}

When I run this program, I get as output: "hello, world" and "hello, world222" for a few seconds. However, after a few seconds, I don't get anything anymore however the program is still running.

What's wrong? Why does the program stop displaying hello, world and hello, world222 ?

</div>
  • 写回答

2条回答 默认 最新

  • dongnong7524 2018-06-18 16:41
    关注

    This is because for now (go 1.10) Go's scheduler is not preemptive, and there is no plans to make it so.

    What this means is that Go's scheduler can stuck in some rare cases, where that there is an infinte loop doing nothing Go's schedule feels like to interupt. And that includes an empty infinite loop.

    To block the goroutine for test, use select{} instead of for {}.

    References:

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

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)