1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| 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 main() { tasks := make(chan string, taskLoad) wg.Add(numberGoroutines) for i := 1; i <= numberGoroutines; i++ { go work(tasks, i) }
for post := 1; post <= taskLoad; post++ { tasks <- fmt.Sprintf("Task:%d", post) } close(tasks) wg.Wait() }
func work(tasks chan string, worker int) { defer wg.Done() for { task, ok := <-tasks if !ok { fmt.Printf("worker:%d shutting down(关闭)\n", worker) return } fmt.Printf("Worker:%d started %s\n", worker, task) sleep := rand.Int63n(100) time.Sleep(time.Duration(sleep) * time.Millisecond) fmt.Printf("Worker:%d completed %s\n", worker, task) } }
|