gpt4 book ai didi

Golang : how to send signal and stop sending values to a goroutine

转载 作者:行者123 更新时间:2023-12-04 03:36:53 27 4
gpt4 key购买 nike

我是新手,我正在尝试学习 goroutines 中信号函数的一些基本用法。我在 go 中有一个无限循环。通过这个 for 循环,我通过 channel 将值传递给 goroutine。 我也有一个阈值,在此之后我会无限期地停止向 goroutine 发送值 (即关闭 channel )。 当达到阈值时,我想打破 for 循环。 以下是我迄今为止尝试过的。
在这个特定的例子中,thresholdValue = 10我想打印来自 0 , ..., 9 的值然后停止。
我关注了 this post on mediumthis post on stackoverflow .我从这些帖子中挑选了我可以使用的元素。
这就是我目前所做的。 在我的代码的 main 函数中,我故意使 for 循环成为无限循环。我的主要目的是学习如何使用 goroutine readValues()取阈值,然后无限期地停止 channel 中的值传输。

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 仍然没有达到阈值。我会很感激任何关于我应该如何从这里开始的方向。

最佳答案

为了表示诚意,这是改写的程序。

package main

import (
"log"
"sync"
"time"
)

func main() {
ch := make(chan int, 5) // capacity increased for demonstration
thresholdValue := 10

var wg sync.WaitGroup
wg.Add(1)
go func() {
readValues(ch)
wg.Done()
}()

for i := 0; i < thresholdValue; i++ {
ch <- i
}
close(ch)
log.Println("sending done.")
wg.Wait()

}

func readValues(ch chan int) {
for value := range ch {
<-time.After(time.Second) // for demonstratin purposes.
log.Println(value)
}
}
在这个版本中 readValues退出 因为 for循环确实退出了 main已关闭 ch .
换句话说,停止条件生效并触发退出序列(信号 end of input 然后等待处理完成)

关于Golang : how to send signal and stop sending values to a goroutine,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66720270/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com