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

Viewed 749

I am new to go and I am trying to learn some basic use of signal functions in goroutines. I have an infinite for loop in go. Through this for loop, I pass values to a goroutine through a channel. I also have a threshold value after which I will like to stop sending values indefinitely to the goroutine (i.e. close the channel). When the threshold value is reached, I will like to break the for loop. Following is what I have tried so far.

In this particular example, thresholdValue = 10 and I would like to print values from 0 , ..., 9 and then stop.

I followed this post on medium and this post on stackoverflow. I picked elements from these posts which I could use.

This is what I have done at the present. In the main function of my code, I purposefully make the for loop an infinite loop. My main intention is to learn how to have the goroutine readValues() take the threshold value and then stop transmission of values indefinitely in the 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)
        }
    }
}

The goroutine in my code still misses the threshold. I will appreciate any direction as to how I should proceed from here.

1 Answers

to show good faith, this is the program rewritten.

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)
    }
}

In this version readValues exits because the for loop did exit and that main closed ch.

In other words a stop condition take effects and triggers the exit sequence (signal end of input then wait for the processing to finish)

Related