Find odd and even numbers using goroutines and channels
The below program starts two Goroutines. These two Goroutines now run concurrently. We created two unbuffered channels and passed them to goroutines as argument with the values received by the channels.
Example
package main
import (
"fmt"
)
func main() {
var intSlice = []int{91, 42, 23, 14, 15, 76, 87, 28, 19, 95}
chOdd := make(chan int)
chEven := make(chan int)
go odd(chOdd)
go even(chEven)
for _, value := range intSlice {
if value%2 != 0 {
chOdd <- value
} else {
chEven <- value
}
}
}
func odd(ch <-chan int) {
for v := range ch {
fmt.Println("ODD :", v)
}
}
func even(ch <-chan int) {
for v := range ch {
fmt.Println("EVEN:", v)
}
}
ODD : 91
ODD : 23
EVEN: 42
EVEN: 14
EVEN: 76
ODD : 15
ODD : 87
ODD : 19
ODD : 95
Most Helpful This Week
Top Programming Languages Behind Blockchain App Development
Struct Instantiation using new keyword
Interface embedding and calling interface methods from another package in Go (Golang)
Go program to find CNAME record of a domain
Goroutines Channels order of execution
Golang program to read XML file into struct
Program in Go language to Calculate Average Using Arrays
How to declare Interface Type in Go Programming Language
GO Program to Find the Largest Number Among Three Numbers
How do you handle HTTP server health checks in Go?