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

yinshidaoshi · · 1515 次点击
三楼写法确实不错
#7
更多评论
试试这样: ```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