先贴代码,有错误请指正
package main
import (
"log"
"sync"
"time"
)
var (
task chan int = make(chan int, 10)
done chan int = make(chan int, 10)
wg_task sync.WaitGroup
wg_done sync.WaitGroup
)
func produce(task_count int) {
defer wg_task.Done()
for i := 0; i < task_count; i++ {
task <- i
log.Printf("send task : [%d]", i)
}
close(task)
}
func consumer(i int) {
defer wg_task.Done()
for {
v, ok := <-task
log.Printf("recv task [%d]: [%d] [%v]", i, v, ok)
if !ok {
break
}
done <- v
time.Sleep(20 * time.Millisecond)
}
}
func consumer_done() {
defer wg_done.Done()
for {
v, ok := <-done
log.Printf("finished : [%d] [%v]", v, ok)
if !ok {
break
}
}
}
func main() {
wg_task.Add(1)
go produce(1000)
for i := 0; i < 10; i++ {
wg_task.Add(1)
go consumer(i)
}
wg_done.Add(1)
go consumer_done()
wg_task.Wait()
close(done)
wg_done.Wait()
}