初学乍练,求教怎么让协程交替执行

yinshidaoshi · · 1510 次点击
```go package main func main() { ch := make(chan int) exit := make(chan struct{}) go func() { for i := 1; i <= 20; i++ { println("g1:", <-ch) i++ ch <- i } }() go func() { defer func() { close(ch) close(exit) }() for i := 0; i < 20; i++ { i++ ch <- i println("g2:", <-ch) } }() <-exit } ```
#3
更多评论
试试这样: ```go func main() { runtime.GOMAXPROCS(1) c1 := make(chan struct{}, 1) c2 := make(chan struct{}, 1) for i := 1; i <= 10; i++ { go func(i int) { <-c1 fmt.Println(2*i - 1) c2 <- struct{}{} }(i) } for i := 1; i <= 10; i++ { go func(i int) { <-c2 fmt.Println(2 * i) c1 <- struct{}{} }(i) } c1 <- struct{}{} c2 <- struct{}{} time.Sleep(3 * time.Second) } ```
#1
试试我的歪招,哈哈 ```go package main import ( "fmt" "time" ) func main() { c1 := make(chan int) c2 := make(chan int) go func() { for i := 1; i <= 10; i++ { <-c1 go func(i int) { fmt.Println(2*i - 1) c2<-1 }(i) } }() go func() { for i := 1; i <= 10; i++ { <-c2 go func(i int) { fmt.Println(2 * i) c1 <- 1 }(i) } }() c1<-1 time.Sleep(3 * time.Second) } ```
#2