douxiao0400 2013-07-30 17:13
浏览 19
已采纳

去例行阻止其他人[重复]

This question already has an answer here:

The following code run forever instead of stopping one second after the beginning. The go routine with the infinite loop seems to prevent the other one from sending to the timeout channel. Is that normal ?

 func main(){
   timeout:=make(chan int)
   go func(){
      time.SLeep(time.Second)
      timeout<-1
    }()

    res:=make(chan int)
    go func(){
        for{
        }
        res<-1
    }()
    select{
        case<-timeout:
            fmt.Println("timeout")
        case<-res:
            fmt.Println("res")
    }
}
</div>
  • 写回答

2条回答 默认 最新

  • dongsuoxi1790 2013-07-30 17:57
    关注

    Short answer: yes.

    The current implementation uses cooperative scheduling among goroutines. This means that a goroutine must hand off execution to the scheduler for another goroutine to run. There is hope in the future to use a preemptive scheduler which will not have this limitation.

    Goroutines yield to the scheduler when any of the following happens (may not be a comprehensive list):

    • unbuffered chan send/recv
    • syscalls (includes file/network reads and writes)
    • memory allocation
    • time.Sleep() is called
    • runtime.Gosched() is called

    The last one allows you to manually yield to the scheduler when you have a very processor intensive loop. I have never found a need for it because just about everything I use has enough communication (channels or system io) that my programs never get stuck.

    There is also GOMAXPROCS which you will probably hear as a solution to this. While it would allow all your goroutines to run by putting them in different threads, the garbage collector would eventually try to run and stop the world. When it stops the world, no goroutines are allowed to run and if the high cpu goroutines never yield, the GC will block goroutines forever but never run.

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

报告相同问题?

悬赏问题

  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line