协程交替执行,使其能顺序输出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"
"time"
)
func main() {
waitOdd := make(chan struct{}, 1)
waitEnev := make(chan struct{}, 1)
waitEnev <- struct{}{}
go odd(waitOdd, waitEnev)
go enev(waitOdd, waitEnev)
time.Sleep(3 * time.Minute)
}
func odd(waitodd, waitenev chan struct{}) {
for i := 0; i < 10; i++ {
<-waitodd
fmt.Println(i*2 + 1)
waitenev <- struct{}{}
}
}
func enev(waitodd, waitenev chan struct{}) {
for i := 0; i < 10; i++ {
<-waitenev
fmt.Println(i * 2)
waitodd <- struct{}{}
}
}
```
#4
更多评论
试试这样:
```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