I have module that has a long running go routine in it that doesn't complete until the end of the program.
I have a for loop that spawns other routines that feed into the channel.
The code is bulky so here is an example that does basically the same thing.
package main
import (
"fmt"
"sync"
"time"
)
func main() {
channel := someFunc()
//unrelated routine
go func() {
time.Sleep(1000 * time.Hour)
}()
for resp := range channel {
fmt.Println(resp)
}
}
func someFunc() chan int {
var wg sync.WaitGroup
t := make(chan int, 10)
arr := []int{1, 2, 3, 4, 5, 6, 7, 8}
for _, i := range arr {
wg.Add(1)
go func(i int) {
defer wg.Done()
time.Sleep(time.Duration(i) * time.Second)
t <- i
}(i)
}
wg.Wait()
close(t)
return t
}
Removing the wait groups and close()
(not having this causes the program to run forever) causes the program to run forever, but having them blocks the channel until all routines finish. How can I send data to the channel without making the program run indefinitely?
PS: the long running routine is in an imported module I do not have control over.
The best way to do this is by adding another go routine. This allows the program to asynchronously wait to close the program.
package main
import (
"fmt"
"sync"
"time"
)
func main() {
channel := someFunc()
//unrelated routine
go func() {
time.Sleep(1000 * time.Hour)
}()
for resp := range channel {
fmt.Println(resp)
}
}
func someFunc() chan int {
var wg sync.WaitGroup
t := make(chan int, 10)
arr := []int{1, 2, 3, 4, 5, 6, 7, 8}
for _, i := range arr {
wg.Add(1)
go func(i int) {
defer wg.Done()
time.Sleep(time.Duration(i) * time.Second)
t <- i
}(i)
}
go func() {
defer close(t)
wg.Wait()
}()
return t
}