Golang:如何发送信号并停止向goroutine发送值

我是新手,我正在尝试学习信号函数在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 仍然错过了阈值。我将赞赏关于我应该如何从这里开始的任何指导。


慕后森
浏览 145回答 1
1回答

幕布斯6054654

为了表示诚意,这是程序重写的。package mainimport (&nbsp; &nbsp; "log"&nbsp; &nbsp; "sync"&nbsp; &nbsp; "time")func main() {&nbsp; &nbsp; ch := make(chan int, 5) // capacity increased for demonstration&nbsp; &nbsp; thresholdValue := 10&nbsp; &nbsp; var wg sync.WaitGroup&nbsp; &nbsp; wg.Add(1)&nbsp; &nbsp; go func() {&nbsp; &nbsp; &nbsp; &nbsp; readValues(ch)&nbsp; &nbsp; &nbsp; &nbsp; wg.Done()&nbsp; &nbsp; }()&nbsp; &nbsp; for i := 0; i < thresholdValue; i++ {&nbsp; &nbsp; &nbsp; &nbsp; ch <- i&nbsp; &nbsp; }&nbsp; &nbsp; close(ch)&nbsp; &nbsp; log.Println("sending done.")&nbsp; &nbsp; wg.Wait()}func readValues(ch chan int) {&nbsp; &nbsp; for value := range ch {&nbsp; &nbsp; &nbsp; &nbsp; <-time.After(time.Second) // for demonstratin purposes.&nbsp; &nbsp; &nbsp; &nbsp; log.Println(value)&nbsp; &nbsp; }}在此版本中退出,因为循环确实退出并且关闭了。readValuesformainch换句话说,停止条件生效并触发退出序列(信号然后等待处理完成)end of input
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go