【发布时间】:2019-12-24 04:32:17
【问题描述】:
我在 goroutine 中使用频道时遇到问题。
var test = make(chan string)
func main() {
go initChan()
for i := 0; i < 2; i++ {
go readChan()
}
var input string
fmt.Scanln(&input)
}
func initChan() {
for i := 0; i < 100; i++ {
test <- "Iteration num: " + strconv.Itoa(i)
time.Sleep(time.Second * 5)
}
}
func readChan() {
for {
message := <- test
log.Println(message)
}
}
输出:
2019/12/24 08:21:17 Iteration num: 0
2019/12/24 08:21:22 Iteration num: 1
2019/12/24 08:21:27 Iteration num: 2
2019/12/24 08:21:32 Iteration num: 3
2019/12/24 08:21:37 Iteration num: 4
2019/12/24 08:21:42 Iteration num: 5
................................
我需要在不等待更新测试变量的情况下读取线程。 现在每个 readChan() 都在等待 initChan() 更新测试变量。
是否有可能使 readChan() 线程一次工作而无需等待每个线程的 initChan()?
【问题讨论】:
标签: multithreading go goroutine