channel面试题。请附上答案,看谁的简单。来玩儿~~~~

xmge · · 1606 次点击
func main() { var ( arra = []int64{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13} arrb = []string{"a", "b", "c", "d", "e", "f"} ok = make(chan bool, 1) num = make(chan bool, 1) letter = make(chan bool, 1) ) go printSlice(arra, num, letter, ok) go printSlice(arrb, letter, num, ok) num <- true <-ok var ctn = true for ctn { select { case <-ok: ctn = false case <-num: letter <- true case <-letter: num <- true } } } func printSlice(slice interface{}, in, out, ok chan bool) { value := reflect.ValueOf(slice) for i := 0; i < value.Len(); i++ { <-in fmt.Println(value.Index(i).Interface()) out <- true } ok <- true } ![659DD080-54D0-404b-A9B2-7CDB431908F4.png](https://static.studygolang.com/181204/f305b81897d3ca4b2c2e56b00d033564.png)
#40
更多评论
``` func DataIn(a []int64,b []string,ch chan interface{},wg *sync.WaitGroup){ for i:=0;i<4;i++{ ch<-a[i] ch<-b[i] } close(ch) wg.Done() } func DataOut(ch chan interface{},wg *sync.WaitGroup){ for v:=range ch{ fmt.Println(v) } wg.Done() } func main(){ var wg sync.WaitGroup arra := []int64{1,2,3,4} arrb := []string{"a","b","c","d"} ch:=make(chan interface{}) wg.Add(2) go DataIn(arra,arrb,ch,&wg) go DataOut(ch,&wg) wg.Wait() } ```
#1
``` package main import ( "fmt" "sync" ) func main() { var ( a = []interface{}{1, 2, 3, 4, 5, 6} b = []interface{}{"a", "b", "c", "d", "e"} wg sync.WaitGroup cha = make(chan struct{}, 1) chb = make(chan struct{}, 1) ) wg.Add(2) go Run(&wg, a, cha, chb) go Run(&wg, b, chb, cha) chb <- struct{}{} wg.Wait() } func Run(group *sync.WaitGroup, data []interface{}, selfChan chan struct{}, peerChan chan struct{}) { for _, d := range data { if _, ok := <-peerChan; !ok { fmt.Println(d) continue } fmt.Println(d) selfChan <- struct{}{} } close(selfChan) group.Done() } ```
#2