package main
import (
"fmt"
"sync"
"time"
)
var wg sync.WaitGroup
func writeCh(ch chan<- int) {
for i := 1; i <= 10; i++ {
ch <- i
fmt.Println("写入-", i)
time.Sleep(time.Millisecond * 50)
}
close(ch)
wg.Done()
}
func readCh(ch <-chan int) {
for val := range ch {
fmt.Println("读取-", val)
time.Sleep(time.Millisecond * 100)
}
wg.Done()
}
func main() {
var ch = make(chan int, 10)
wg.Add(1)
go writeCh(ch)
wg.Add(1)
go readCh(ch)
wg.Wait()
}
执行结果
写入- 1
读取- 1
写入- 2
写入- 3
读取- 2
写入- 4
读取- 3
写入- 5
写入- 6
读取- 4
写入- 7
写入- 8
读取- 5
写入- 9
读取- 6
写入- 10
读取- 7
读取- 8
读取- 9
读取- 10
网友评论