I'm learning about channels and concurrency in GO and I'm stuck on a task. I want to function that passes a slice, filters the numbers and then prints the channel values. The issue is that when I use the channel it deadlocks the program. This is my code:
package main
import (
"fmt"
)
func processOdd(inputs []int) chan int {
oddValues := make(chan int)
for _, numbers := range inputs {
go func(num int) {
if num%2 != 0 {
oddValues <- num
}
}(numbers)
}
return oddValues
}
func processEven(inputs []int) chan int {
evenValues := make(chan int)
for _, numbers := range inputs {
go func(num int) {
if num%2 == 0 {
evenValues <- num
}
}(numbers)
}
return evenValues
}
func main() {
inputs := []int{1, 17, 34, 56, 2, 8}
evenCH := processEven(inputs)
for range inputs {
fmt.Print(<-evenCH)
}
}
CodePudding user response:
Close the channel when done sending values:
func processEven(inputs []int) chan int {
evenValues := make(chan int)
var wg sync.WaitGroup
for _, num := range inputs {
wg.Add(1)
go func(num int) {
defer wg.Done()
if num%2 == 0 {
evenValues <- num
}
}(num)
}
go func() {
wg.Wait()
close(evenValues)
}()
return evenValues
}
The code uses a WaitGroup to wait for the senders to complete.
Loop receiving values until the channel is closed:
func main() {
inputs := []int{1, 17, 34, 56, 2, 8}
evenCh := processEven(inputs)
for num := range evenCh {
fmt.Println(num)
}
}
Range on a channel loops until the channel is closed.