package main
import (
"fmt"
"sync"
)
var wg sync.WaitGroup
func main() {
evenCh, oddCh := make(chan bool, 1), make(chan bool, 1)
defer close(evenCh)
defer close(oddCh)
wg = sync.WaitGroup{}
wg.Add(1)
go printNumbersSequentially(1, 10, oddCh, evenCh)
evenCh <- true
wg.Wait()
}
// 合并后的打印方法
func printNumbersSequentially(start, end int, oddCh, evenCh chan bool) {
for i := start; i <= end; i++ {
if i%2 == 0 { // 偶数
<-oddCh
fmt.Println(i)
evenCh <- true
} else { // 奇数
<-evenCh
fmt.Println(i)
oddCh <- true
}
}
wg.Done()
}
标签:wg,奇偶,evenCh,defer,打印,sync,Golang,oddCh
From: https://www.cnblogs.com/qcy-blog/p/18135579