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換成無緩衝的,結果看上去有點奇怪