duanqin4238 2016-03-31 07:55
浏览 182
已采纳

Golang:select语句在不应该退出时退出

I'm trying to create a program that prints "Eat", "Work", "Sleep" every 3rd, 8th, and 24th second respectively. Here is my code:

package main

import (
"fmt"
"time"
)

func Remind(text string, delay time.Duration) <-chan string { //channel only for receiving strings
    ch := make(chan string) // buffered/unbuffered?
    go func() {
        for {
            msg := "The time is " + time.Now().Format("2006-01-02 15:04:05 ") + text
            ch <- msg
            time.Sleep(delay) // waits according to specification
        }
    }()
    return ch
}

func main() {
    ch1 := Remind("Eat", 1000*1000*1000*3) // every third second    
    ch2 := Remind("Work", 1000*1000*1000*8) // every eighth second
    ch3 := Remind("Sleep", 1000*1000*1000*24) // every 24th second
    select { // chooses one channel that is not empty. Should run forever (?)
        case rem1 := <-ch1:
            fmt.Println(rem1)
        case rem2 := <-ch2:
            fmt.Println(rem2)
        case rem3 := <-ch3:
            fmt.Println(rem3)
    }
}

The problem with it is that it stops running immediately after printing the time followed by "Eat". In other examples I have read, the select statement goes on forever. Why doesn't it now?

  • 写回答

2条回答 默认 最新

  • duange051858 2016-03-31 07:57
    关注

    I don't know where you've read that the select goes on forever, but it doesn't.

    Once a case is executed, the select statement is "done". If none of the communication operations specified in cases can proceed and there is no default branch, select will block, for as long as any of the com. ops can proceed. But once a case is executed, select does not repeat.

    Read the relevant section from the spec: Select statements.

    Put it in an endless for to make it repeat forever:

    for {
        select { // chooses one channel that is not empty. Should run forever (?)
        case rem1 := <-ch1:
            fmt.Println(rem1)
        case rem2 := <-ch2:
            fmt.Println(rem2)
        case rem3 := <-ch3:
            fmt.Println(rem3)
        }
    }
    

    As a sidenote:

    You can create time.Duration values much easier, using constants from the time package:

    ch1 := Remind("Eat", 3*time.Second)    // every third second
    ch2 := Remind("Work", 8*time.Second)   // every eighth second
    ch3 := Remind("Sleep", 24*time.Second) // every 24th second
    

    You may also want to check out the time.Ticker type which is for tasks similar to your Remind() function.

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

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?