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

xmge · · 1622 次点击
<a href="/user/CNbluer" title="@CNbluer">@CNbluer</a> 也是发完了,才发现原来跑题了。哈哈
#33
更多评论
``` func DataIn(a []int64,b []string,ch chan interface{},wg *sync.WaitGroup){ for i:=0;i&lt;4;i++{ ch&lt;-a[i] ch&lt;-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{&#34;a&#34;,&#34;b&#34;,&#34;c&#34;,&#34;d&#34;} ch:=make(chan interface{}) wg.Add(2) go DataIn(arra,arrb,ch,&amp;wg) go DataOut(ch,&amp;wg) wg.Wait() } ```
#1
``` package main import ( &#34;fmt&#34; &#34;sync&#34; ) func main() { var ( a = []interface{}{1, 2, 3, 4, 5, 6} b = []interface{}{&#34;a&#34;, &#34;b&#34;, &#34;c&#34;, &#34;d&#34;, &#34;e&#34;} wg sync.WaitGroup cha = make(chan struct{}, 1) chb = make(chan struct{}, 1) ) wg.Add(2) go Run(&amp;wg, a, cha, chb) go Run(&amp;wg, b, chb, cha) chb &lt;- struct{}{} wg.Wait() } func Run(group *sync.WaitGroup, data []interface{}, selfChan chan struct{}, peerChan chan struct{}) { for _, d := range data { if _, ok := &lt;-peerChan; !ok { fmt.Println(d) continue } fmt.Println(d) selfChan &lt;- struct{}{} } close(selfChan) group.Done() } ```
#2