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
Program in Go language to Calculate Standard Deviation using Math package
Declaration of a struct type
How to Convert string to integer type in Go?
Golang program for implementation of Radix Sort
How to create Slice of Struct in Golang?
Program in Go language to Calculate Average Using Arrays
This sample program demonstrates how to create multiple goroutines and how the goroutine scheduler behaves with three logical processors.
Find out how many logical processors used by current process
Illustration of the dining philosophers problem in Golang
Golang read csv file into struct