package main
import (
"fmt"
"math/rand"
"sync"
"time"
)
const (
numberGoroutines = 4 //要使用的goroutine數量
taskLoad = 20 //要處理的工做數量
)
var wg sync.WaitGroup
//init 初始化包 在運行其餘代碼以前執行
func init(){
rand.Seed(time.Now().Unix())
}
//入口函數
func main(){
//建立一個有緩衝的通道來管理工做
tasks :=make(chan string,taskLoad)
//啓動GoRoutine來處理工做
wg.Add(numberGoroutines)
for gr :=1;gr<=numberGoroutines ;gr++ {
go worker(tasks,gr)
}
//增長一組要完成的工做
for post :=10; post<taskLoad;post++ {
tasks <- fmt.Sprintf("Task: %d\n",post)
}
//完成以後關閉GoRoutine
close(tasks)
//等待全部工做完成
wg.Wait()
}
//工做函數
func worker(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)
}
}
複製代碼
H-----E-----L-----L-----O-----
aaaa:0
aaaa:1
aaaa:2
aaaa:3
aaaa:4
aaaa:5
aaaa:6
aaaa:7
aaaa:8
aaaa:9賦值後:100 --- 200Multiply 2 * 5 * 6 = 60
Process finished with exit code 0
複製代碼
. . .json