dongya1875 2018-02-12 16:12
浏览 33
已采纳

goroutine不再安排

I'm learning golang. I have a goroutine to print variable i and after it I write a deadloop. But when var i up to 491519(or some other value), there is no output on the terminal. It looks like the goroutine which print var i is no longer be scheduled, the CPU execute the deadloop all the way after output 491519. Who can tell me the reason?
thanks.

My code:

package main

import (
    "fmt"
    "runtime"
)

func main() {
        go func() {
                i := 1
                for {
                        fmt.Println(i)
                        i = i + 1
                }
        }()
        runtime.GOMAXPROCS(4)
        for {
        }
}

I'd like to add that:
When I add fmt.Println("ABC") in the last deadloop, the alternation of ABC or i output on the terminal forever.

my go version: go version go1.9.1 darwin/amd64

  • 写回答

2条回答 默认 最新

  • dongyu9667 2018-02-13 10:47
    关注

    Goroutines are scheduled by Go runtime, therefore there are some limitations in comparison to the processes scheduling done by an operating system. An operating system can preempt processes by using timed interrupts, Go runtime cannot preempt goroutines.

    Go runtime schedules another goroutine when goroutine

    • makes channel operation (this includes select statement, even empty)
    • make system call
    • explicitly calls runtime.Gosched

    Setting GOMAXPROCS does not help much. Take a look at following program. It will use all processors and will stay in tight busy loops.

    func runForever() {
       for {
       }
    }
    
    func main() {
        for i := 0; i < runtime.GOMAXPROCS(-1); i++ {
            go runForever()
        }
        time.Sleep(time.Second)
    }
    

    There are few ways of fixing your program:

    go func() {
        for i:= 1; true; i++ {
            fmt.Println(i)
        }
    }()
    
    for {
        runtime.Gosched()
    }
    

    Or

    go func() {
        for i:= 1; true; i++ {
            fmt.Println(i)
        }
    }()
    
    select {
    }
    

    The work on improving the case of tight loops is ongoing.

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

报告相同问题?

悬赏问题

  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程