dpikoto468637 2019-04-25 23:22
浏览 154

vs vs无限循环,没有时间。Sleep()[重复]

This question already has an answer here:

I've got a goroutine that's playing some audio infinitely play(). In order to keep the play() alive, I've got the calling function running an infinite for loop afterward.

The unexpected thing is that a barebones loop does not seem to let the function play infinitely and I'm at a loss as to why. However, if I add a simple time.Sleep(time.Second) into the body of the for-loop, it runs seemingly infinitely. Any idea as to why?

To visualize:

func PlaysForAFewSeconds() {
    go play()
    for {
    }
}

^plays for a few seconds but never breaks out

func PlaysForever() {
    go play()
    for {
        time.Sleep(time.Second)
    }
}

^ plays forever.

I'm guessing that this has something to do with how play() is implemented but I'm hoping this is a common enough problem that someone recognizes this symptom. Thanks.

</div>
  • 写回答

1条回答 默认 最新

  • doushuo8677 2019-04-26 01:56
    关注

    The assembly that for { } generates is jmp self, where self is the location of the jmp instruction. In other words, the CPU will just keep running jmp instructions as fast as it can. The CPU can run n instructions per second, and it doesn't matter if this is a useless jmp or an actually useful instruction.

    This is known as a "busy wait" or "spin lock", and this behaviour is not specific to Go. Most (all?) programming languages behave like this.

    There are some uses for such loops, but in Go they can often be replaced with channels:

    // Simulate a function that takes 1s to complete.
    func play(ch chan struct{}) {
        fmt.Println("play")
        time.Sleep(1 * time.Second)
        ch <- struct{}{}
    }
    
    func PlaysForAFewSeconds() {
        wait := make(chan struct{})
        go play(wait)
        <-wait
    }
    
    func PlaysForever() {
        wait := make(chan struct{})
        for {
            go play(wait)
            <-wait
        }
    }
    

    Reading from a channel (<-wait) is blocking and doesn't use any CPU. I used an empty anonymous struct, which looks a bit ugly, as that doesn't allocate any memory.

    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大