code
package main
import (
"fmt"
"sync"
)
func Printer(num int) {
wg := sync.WaitGroup{}
wg.Add(2)
// 无buffer 2个g同步发送和接收
ch := make(chan struct{})
go func() {
defer wg.Done()
for i := 1; i <= num; i++ {
ch <- struct{}{}
//奇数
if i%2 == 1 {
fmt.Println("g1打印:",i)
}
}
}()
go func() {
defer wg.Done()
for i := 1; i <= num; i++ {
<- ch
//偶数
if i%2 == 0 {
fmt.Println("g2打印:",i)
}
}
}()
wg.Wait()
}
func main() {
fmt.Println("start ")
Printer(50)
fmt.Println("end ")
}
output
start
g1打印: 1
g2打印: 2
g1打印: 3
g2打印: 4
g1打印: 5
g2打印: 6
g1打印: 7
g2打印: 8
g1打印: 9
g2打印: 10
g1打印: 11
g2打印: 12
g1打印: 13
g2打印: 14
g1打印: 15
g2打印: 16
g1打印: 17
g2打印: 18
g1打印: 19
g2打印: 20
g1打印: 21
g2打印: 22
g1打印: 23
g2打印: 24
g1打印: 25
g2打印: 26
g1打印: 27
g2打印: 28
g1打印: 29
g2打印: 30
g1打印: 31
g2打印: 32
g1打印: 33
g2打印: 34
g1打印: 35
g2打印: 36
g1打印: 37
g2打印: 38
g1打印: 39
g2打印: 40
g1打印: 41
g2打印: 42
g1打印: 43
g2打印: 44
g1打印: 45
g2打印: 46
g1打印: 47
g2打印: 48
g1打印: 49
g2打印: 50
end
网友评论