代码如下:
package main
import (
"fmt"
"sync"
)
func doWorker(id int, w worker) {
for n := range w.in {
fmt.Printf("Worker %d received %c\n", id, n)
w.done()
}
}
type worker struct {
in chan int
done func()
}
func createWorker(id int, wg *sync.WaitGroup) worker {
w := worker{
in: make(chan int),
done: func() {
wg.Done()
},
}
// Worker
go doWorker(id, w)
return w
}
func chanDemo() {
var workers [10]worker
var wg sync.WaitGroup
// 初始化worker
for i, _ := range workers {
workers[i] = createWorker(i, &wg)
}
wg.Add(20)
// 任务1
for i, worker := range workers {
worker.in <- 'a' + i
}
// 任务2
for i, worker := range workers {
worker.in <- 'A' + i
}
wg.Wait()
}
func main() {
chanDemo()
}
评论前必须登录!
注册