func tickerSourceChan(ack <-chan interface{}) chan interface{} { out := make(chan interface{}) ackCounter := uint64(0) go func() { for i := 0; i < 10; i++ { msg := &myMessage{RandomCarNum()} out <- msg fmt.Println("Source sended:", msg,">>",i) } close(out) }() go func() { for element := range ack { fmt.Println("ACK received:", element, ackCounter) ackCounter++ } fmt.Println("Ack closed:",ackCounter) }() return out } 如何检测ack closed
时间: 2024-03-09 12:49:54 浏览: 87
interface功能详解
你可以在 `for` 循环中使用 `range`,当 `ack` 的 channel 被关闭时,`for` 循环会自动结束,如下所示:
```
func tickerSourceChan(ack <-chan interface{}) chan interface{} {
out := make(chan interface{})
ackCounter := uint64(0)
go func() {
defer close(out)
for i := 0; i < 10; i++ {
msg := &myMessage{RandomCarNum()}
out <- msg
fmt.Println("Source sended:", msg, ">>", i)
}
}()
go func() {
for element := range ack {
fmt.Println("ACK received:", element, ackCounter)
ackCounter++
}
fmt.Println("Ack closed:",ackCounter)
}()
return out
}
```
在第二个 goroutine 中,使用 `range` 来遍历 `ack` 的 channel。当 `ack` 的 channel 被关闭时,`range` 循环会自动结束,然后就可以打印 `Ack closed` 并退出 goroutine。
阅读全文