今天面试遇到"两个goroutine 循环打印1~100"
思路是一个goroutine放数据,一个goroutine读数据,可是结果却是乱序的
```golang
func Test_0(t *testing.T) {
//fmt.Println("123")
c1 := make(chan int)
wg := sync.WaitGroup{}
wg.Add(2)
go func() {
for i := 0; i < 10; i += 2 {
c1 <- 1
fmt.Print(i)
}
wg.Done()
}()
go func() {
for i := 1; i < 10; i += 2 {
<-c1
fmt.Print(i)
}
wg.Done()
}()
wg.Wait()
}
```
=== RUN Test_0
0132457689--- PASS: Test_0 (0.00s)
PASS
----------------------------分割线----------------------------------
之后看了晚上的解答,只是循环的时候从+2->++,奇怪?这样就没问题呢?
```golang
func Test_dongchedi(t *testing.T) {
//fmt.Println("123")
c1 := make(chan int)
wg := sync.WaitGroup{}
wg.Add(2)
go func() {
for i := 1; i <= 10; i++ {
c1 <- 1
if i%2 == 1 {
fmt.Print(i)
}
}
wg.Done()
}()
go func() {
for i := 1; i <= 10; i++ {
<-c1
if i%2 == 0 {
fmt.Print(i)
}
}
wg.Done()
}()
//c1 <- 1
wg.Wait()
}
```
=== RUN Test_dongchedi
12345678910--- PASS: Test_0(0.00s)
PASS
有疑问加站长微信联系(非本文作者)