我是新手,我正在努力学习goroutines中信号函数的一些基本用法。我有一个无限的for循环。通过这个for循环,我通过一个通道将值传递给goroutine。我还有一个阈值,在这个阈值之后,我想无限期地停止向goroutine发送值(即关闭通道)。当达到阈值时,我想中断for循环。以下是我迄今为止所做的尝试。
thresholdValue = 100 , ..., 9
我在媒体和stackoverflow上关注了这篇文章。我从这些帖子中挑选了我可以使用的元素。
readValues()
package main
import (
"fmt"
)
func main() {
ch := make(chan int)
quitCh := make(chan struct{}) // signal channel
thresholdValue := 10 //I want to stop the incoming data to readValues() after this value
go readValues(ch, quitCh, thresholdValue)
for i:=0; ; i++{
ch <- i
}
}
func readValues(ch chan int, quitCh chan struct{}, thresholdValue int) {
for value := range ch {
fmt.Println(value)
if (value == thresholdValue){
close(quitCh)
}
}
}
我代码中的goroutine仍然未达到阈值。我很感激你能给我指明今后的方向。