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条)

报告相同问题?

悬赏问题

  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗