协程交替执行,使其能顺序输出1-20的自然数
```go
package main
import (
"fmt"
"time"
)
func main() {
for i:=1;i<=10;i++ {
go func(i int) {
fmt.Println(2*i-1)
}(i)
}
for i:=1;i<=10;i++ {
go func(i int) {
fmt.Println(2*i)
}(i)
}
time.Sleep(3*time.Second)
}```
```go
package main
import "fmt"
func main() {
A := make(chan bool, 1)
B := make(chan bool)
Exit := make(chan bool)
go func() {
for i := 1; i <= 20; i++ {
if ok := <-A; ok {
fmt.Println("A = ", 2*i-1)
B <- true
}
}
}()
go func() {
defer func() {
close(Exit)
}()
for i := 1; i <= 20; i++ {
if ok := <-B; ok {
fmt.Println("B : ", 2*i)
A <- true
}
}
}()
A <- true
<-Exit
}
```
#5
更多评论
试试这样:
```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