【发布时间】:2016-07-19 13:12:14
【问题描述】:
我正在尝试创建一个程序,分别每 3、8 和 24 秒打印一次"Eat"、"Work"、"Sleep"。这是我的代码:
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)
}
}
它的问题是它在打印时间后立即停止运行,然后是"Eat"。在我读过的其他示例中,select 语句永远存在。为什么现在不行了?
【问题讨论】:
标签: select go channel channels