我是新手,我正在尝试学习信号函数在goroutines中的一些基本用法。我有一个无限的for循环。通过这个 for 循环,我通过通道将值传递给 goroutine。我还有一个阈值,之后我想无限期地停止向goroutine发送值(即关闭通道)。当达到阈值时,我想打破 for 循环。以下是我到目前为止尝试过的内容。
在这个特定的例子中,我想从中打印值,然后停止。thresholdValue = 100 , ..., 9
我在medium上关注了这篇文章,在stackoverflow上关注了这篇文章。我从这些帖子中挑选了可以使用的元素。
这就是我现在所做的。在我的代码的主要函数中,我故意使for循环成为无限循环。我的主要目的是学习如何让 goroutine 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 仍然错过了阈值。我将赞赏关于我应该如何从这里开始的任何指导。
幕布斯6054654
相关分类