dongliang1996 2013-08-19 05:37
浏览 20
已采纳

如何休息时间睡眠

I just started picking up Golang a couple days ago and I can't seem to figure out to break out of time.Sleep()...

I can return / break out of the for loop, but the function wont return since Sleep continues doing its thing.

I am guessing the solution is pretty simple, but I can't seem to find the answer.

func main() {
  ticker := time.NewTicker(time.Second * 1)

  go func() {
    for i := range ticker.C {
      fmt.Println("tick", i)
      ticker.Stop()
      break
    }
  }()
  time.Sleep(time.Second * 10)
      ticker.Stop()

  fmt.Println("Hello, playground")
}

Thanks in advance!

  • 写回答

2条回答 默认 最新

  • doulu1544 2013-08-19 06:24
    关注

    It sounds like you want to send the main goroutine a message telling it your other goroutine is complete. For that, channels are the best way to go.

    func main() {
        ticker := time.NewTicker(time.Second)
        done := make(chan bool, 1)
    
        go func() {
            for i := range ticker.C {
                fmt.Println("tick", i)
                ticker.Stop()
                break
            }
    
            done <- true
        }()
    
        timer := time.NewTimer(time.Second/2)
        select {
        case <-done:
            timer.Stop()
        case <-timer.C:
            ticker.Stop()
        }
    
        fmt.Println("Done")
    }
    

    Working example at http://play.golang.org/p/5NFsvC5f7P

    When the timer is greater than ticker, it ticks. When it is less than, all you see is "done".

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

报告相同问题?

悬赏问题

  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害