package main
import (
"fmt"
"strconv"
"time"
)
func generator() chan int {
ch := make(chan int)
go func() {
i := 0
for {
i++
ch <- i
time.Sleep(time.Duration(10) * time.Millisecond)
}
}()
return ch
}
func printer(delay int, square bool, ch chan int) {
for n := range ch {
if (square) {
fmt.Printf("["+strconv.Itoa(n) + "],")
} else {
fmt.Printf("("+strconv.Itoa(n) + "),")
}
time.Sleep(time.Duration(delay) * time.Millisecond)
}
}
func sendToBoth(ch chan int) (ch1 chan int, ch2 chan int) {
ch1 = make(chan int)
ch2 = make(chan int)
go func() {
for {
//n := <- ch
select {
case v := <- ch: //this is the problem point
ch1 <- v //
case v := <- ch: //
ch2 <- v //
}
}
}()
return ch1, ch2
}
func main() {
ch1, ch2 := sendToBoth(generator())
go printer(100, true, ch1) //[]
go printer(200, false, ch2) //()
var name string
fmt.Scan(&name)
}
I want to implement sendToBoth function which gets generated number 1,2,3,... from channel ch and sends it to both ch1 and ch2. But each has a different delay and I don't want one to wait for other to unlock, so I tried to use select, but can't figure out how to ask for If ch1 or ch2 is available at the moment in case clause. Any help?
Output should be like
(1),[1],[2],(2),[3],[4],(3),[5],[6],(4),[7],[8],...