dongsimu4422 2015-10-04 20:11
浏览 34
已采纳

根据时间编写睡眠功能

EDIT: My question is different from How to write my own Sleep function using just time.After? It has a different variant of the code that's not working for a separate reason and I needed explanation as to why.

I'm trying to solve the homework problem here: https://www.golang-book.com/books/intro/10 (Write your own Sleep function using time.After).

Here's my attempt so far based on the examples discussed in that chapter:

package main

import (
        "fmt"
        "time"
)

func myOwnSleep(duration int) {
        for {
                select {
                case <-time.After(time.Second * time.Duration(duration)):
                        fmt.Println("slept!")
                default:
                        fmt.Println("Waiting")
                }
        }
}

func main() {
        go myOwnSleep(3)

        var input string
        fmt.Scanln(&input)
}

http://play.golang.org/p/fb3i9KY3DD

My thought process is that the infinite for will keep executing the select statement's default until the time.After function's returned channel talks. Problem with the current code being, the latter does not happen, while the default statement is called infinitely.

What am I doing wrong?

  • 写回答

1条回答 默认 最新

  • duan0403788996 2015-10-04 20:19
    关注

    In each iteration of your for loop the select statement is executed which involves evaluating the channel operands.

    In each iteration time.After() will be called and a new channel will be created!

    And if duration is more than 0, this channel is not ready to receive from, so the default case will be executed. This channel will not be tested/checked again, the next iteration creates a new channel which will again not be ready to receive from, so the default case is chosen again - as always.

    The solution is really simple though as can be seen in this answer:

    func Sleep(sec int) {
        <-time.After(time.Second* time.Duration(sec))
    }
    

    Fixing your variant:

    If you want to make your variant work, you have to create one channel only (using time.After()), store the returned channel value, and always check this channel. And if the channel "kicks in" (a value is received from it), you must return from your function because more values will not be received from it and so your loop will remain endless!

    func myOwnSleep(duration int) {
        ch := time.After(time.Second * time.Duration(duration))
        for {
            select {
            case <-ch:
                fmt.Println("slept!")
                return // MUST RETURN, else endless loop!
            default:
                fmt.Println("Waiting")
            }
        }
    }
    

    Note that though until a value is received from the channel, this function will not "rest" and just execute code relentlessly - loading one CPU core. This might even give you trouble if only 1 CPU core is available (runtime.GOMAXPROCS()), other goroutines (including the one that will (or would) send the value on the channel) might get blocked and never executed. A sleep (e.g. time.Sleep(time.Millisecond)) could release the CPU core from doing endless work (and allow other goroutines to run).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么