New to go. I am trying to read a map[int][]string
, write the slice of strings into an intermediate channel and then once everything is written, read back all the strings from intermediate channel to another channel and finally read the channel into another goroutine.
I am not able to figure out what is a good non-blocking way to read from the intermediate channel.
package main
import (
"fmt"
)
func f1(c chan []string, q chan int) {
// intermediate channel
ic := make(chan []string, 10)
hmap := map[int][]string{
0: []string{"a", "b", "c"},
1: []string{"d", "e",},
2: []string{"f", "g", "h"},
}
// for every elem in hmap put the values into intermediate channel
for _, v := range hmap {
f2(v, ic)
}
// everything is in intermediate channel by now
// read all the []string and concatenate them into a slice in a
// non-blocking fashion
var strs []string
for v := range ic {
strs = append(strs, v...)
}
// strs := <-ic
fmt.Println(strs)
select {
case c <- strs:
fmt.Println("Received strings.")
default:
fmt.Println("did not receive anything.")
}
q <- 1
}
func f2(v []string, ic chan []string) {
select {
case ic <- v:
fmt.Println("Sent to intermediate channel:", v)
default:
fmt.Println("nothing to send...")
}
}
func f3(c chan []string) {
fmt.Println(<-c)
}
func main() {
c := make(chan []string, 10)
q := make(chan int)
go f1(c, q)
go f3(c)
fmt.Println(<-q) // to wait for the quit to be set
}
go run main.go
to run.
This program goes into deadlock. How can I avoid the deadlock?