Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Processing odd and even values

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading