我觉得快速学习最重要的是理解语言的体系,
哪些技术适用于哪些场景实现,
然后,可以合理的运用。
比如,有缓冲和无缓冲的通道,
自己真正在使用时,会比较少而简单,
面对复杂的通道调度时,
会有更好的开源框架来操作。
正如PYTHON中分布式任务队列,
自己一般不会写多进程程序去操作,
而趋向于celery之类的框架。
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 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()
}
func worker(tasks chan string, worker int) {
defer wg.Done()
for {
task, ok := <-tasks
if !ok {
fmt.Printf("Worker: %d : Shutdown\n", worker)
return
}
fmt.Printf("Worker: %d : Started %s\n", worker, task)
sleep := rand.Int63n(100)
time.Sleep(time.Duration(sleep) * time.Microsecond)
fmt.Printf("Worker: %d : Completed %s\n", worker, task)
}
}