package main
import (
"fmt"
"math/rand"
"sync"
"time"
)
const (
numberGoroutines = 4
taskLoad = 10
)
var wg sync.WaitGroup
func init() {
rand.Seed(time.Now().Unix())
}
func worker(tasks chan string, worker int) {
defer wg.Done()
for {
task, ok := <-tasks
if !ok {
fmt.Printf("Workerr : %d : Shutting Down\n", worker)
return
}
fmt.Printf("Worker : %d : Started work %s\n", worker, task)
sleep := rand.Int63n(100)
time.Sleep(time.Duration(sleep) * time.Microsecond)
fmt.Printf("Worker : %d : Completed %s \n", worker, task)
}
}
func main() {
tasks := make(chan string, 10)
wg.Add(numberGoroutines)
// 开启消费者
for gr := 1; gr <= numberGoroutines; gr++ {
go worker(tasks, gr)
}
// 开启生产者
for post := 1; post <= taskLoad; post++ {
tasks <- fmt.Sprintf("Task : %d", post)
}
close(tasks)
wg.Wait()
}
有一个疑问就是,如果tasks这个channel换成无缓冲的,结果看上去有点奇怪