1 回答
TA贡献1790条经验 获得超9个赞
我终于让它发挥作用了。
package main
import (
"fmt"
"github.com/dchest/uniuri"
"math/rand"
"sync"
"time"
)
var count = 0
func printMe(msg string) {
time.Sleep(1 * time.Second)
fmt.Println(count, msg)
}
func makeMePrint(wg *sync.WaitGroup, ch chan string) {
wg.Add(1)
defer wg.Done()
for s := range ch {
count++
printMe(s)
}
}
func writePrint(wg *sync.WaitGroup, ch chan<- string) {
wg.Add(1)
defer wg.Done()
fmt.Println("Starting to insert data in channel")
for i := 1; i <= rand.Intn(30); i++ {
s := uniuri.New()
ch <- s
}
fmt.Println("We are done inserting all data in the channel")
close(ch)
}
func main() {
wg := &sync.WaitGroup{}
var ch = make(chan string)
go writePrint(wg, ch)
go makeMePrint(wg, ch)
time.Sleep(1 * time.Second)
wg.Wait()
}
- 1 回答
- 0 关注
- 112 浏览
添加回答
举报