golang奇偶数交叉打印
作者:互联网
golang奇偶数交叉打印
package main
import (
"fmt"
"sync"
)
func main() {
// 定义打印数据
numberList := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
// 定义两个channel用于互相通信
ch1 := make(chan bool)
ch2 := make(chan bool)
// 定义waitGroup实现同步
wg := &sync.WaitGroup{}
wg.Add(2)
go func() {
Print1(numberList, wg, ch1, ch2)
}()
go func() {
Print2(numberList, wg, ch1, ch2)
}()
wg.Wait()
}
func Print1(numberList []int, wg *sync.WaitGroup, ch1, ch2 chan bool) {
defer wg.Done()
for _, v := range numberList {
if v%2 != 0 {
fmt.Println("goroutine 1 printer:", v)
ch2 <- true
<-ch1
}
}
}
func Print2(numberList []int, wg *sync.WaitGroup, ch1, ch2 chan bool) {
defer wg.Done()
for _, v := range numberList {
if v%2 == 0 {
<-ch2
fmt.Println("goroutine 2 printer:", v)
ch1 <- true
}
}
}
标签:wg,奇偶,打印,chan,golang,ch1,ch2,numberList,func 来源: https://www.cnblogs.com/tomtellyou/p/14817739.html