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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?