When you use unbuffered channel, the channel content will be handled in order so next value is blocked until the previous is handled. See the output below. In this example we are going to use goroutines to handle specific jobs in their own channels. Odd numbers are handled with odd channel and even numbers are handled with even channel.


Example


package main

import (
"fmt"
"math/rand"
"time"
)

var (
limit = 9
values = []int{0, 1, 2, 3, 4, 5, 6}
)

func main() {
// You can use buffered version if you wish.
chOd := make(chan int)
chEv := make(chan int)

go odd(chOd)
go even(chEv)

pick(chOd, chEv)
}

// Will write numbers to relevant channels.
func pick(chOd, chEv chan <- int) {
rand.Seed(time.Now().UnixNano())

for i := 1; i <= limit; i++ {
v := values[rand.Intn(len(values))]
fmt.Println("PIK", i, ":", v)

if v%2 != 0 {
chOd <- v
} else {
chEv <- v
}
}
}

// Will block until the channel is empty.
func odd(ch <- chan int) {
for v := range ch {
fmt.Println("ODD", v)
}
}

// Will block until the channel is empty.
func even(ch <- chan int) {
for v := range ch {
fmt.Println("EVE", v)
}
}

PIK 1 : 4
PIK 2 : 5
EVE 4
ODD 5
PIK 3 : 0
PIK 4 : 6
EVE 0
PIK 5 : 2
EVE 6
EVE 2
PIK 6 : 6
PIK 7 : 3
EVE 6
PIK 8 : 3
ODD 3
ODD 3
PIK 9 : 0
EVE 0