## 请听题:
将以下数组打印成如下结果,要求:使用两个goroutine来分开打印
```
数组:
arra := []int64{1,2,3,4}
arrb := []string{"a","b","c","d"}
```
```
结果:
1
a
2
b
3
c
4
d
```
```golang
package main
import (
"fmt"
)
func crossPrint(s1 []int64, s2 []string) <-chan struct{} {
c1 := make(chan int)
c2 := make(chan struct{})
c3 := make(chan struct{})
index := 0
go func() {
for {
select {
case c1 <- index:
fmt.Println(s1[index])
index++
c2 <- struct{}{}
}
}
}()
go func() {
for {
select {
case i := <-c1:
<-c2
fmt.Println(s2[i])
if i == len(s2)-1 {
c3 <- struct{}{}
}
}
}
}()
return c3
}
func main() {
s1 := []int64{1, 2, 3, 4}
s2 := []string{"a", "b", "c", "d"}
<-crossPrint(s1, s2)
}
```
#35
更多评论
```
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