【发布时间】:2017-03-12 13:32:09
【问题描述】:
你好,我了解了 goroutine 和 channel。 我对通道做了一些实验,我通过通道发送数据并尝试在 2 个函数中捕获它。但我的第二个功能没有运行
这是我的代码:
package main
import (
"fmt"
"os"
"time"
)
func timeout(duration int, ch chan<- bool) {
time.AfterFunc(time.Duration(duration)*time.Second, func() {
ch <- true
})
}
func watcher(duration int, ch <-chan bool) {
<-ch
fmt.Println("\nTimeout! no Answer after", duration, "seconds")
os.Exit(0)
}
func watcher2(duration int, ch <-chan bool) {
<-ch
fmt.Println("This is watcher 2 as a second receiver")
}
func main() {
var data = make(chan bool)
var duration = 5
go timeout(duration, data)
go watcher(duration, data)
go watcher2(duration, data)
var input string
fmt.Print("What is 725/25 ? ")
fmt.Scan(&input)
if input == "29" {
fmt.Println("Correct")
} else {
fmt.Println("Wrong!")
}
}
你能告诉我一些关于它的解释吗? 谢谢
【问题讨论】:
-
在频道上发送的项目只会收到一次。