This is a creation in Article, where the information may have evolved or changed.
In the process of Golang writing service program, if each time to fight to start a goroutine to handle the task, processing a task and then exit, this will inevitably lead to waste of resources. Building a working Goroutine pool to handle tasks is less than resource utilization, and the specific situation requires a comparative test.
First define the work Goroutine pool, internally defined two variables, one is the task queue, and the number of goroutine to be started
typestruct { tasks <-chan *string//任务队列长度 int //启动goroutine的数目}
Implementing the Work function
func (p *WorkerPool) Run() { var wg sync.WaitGroup for i := 0; i < p.poolSize; i++ { wg.Add(1) gofunc() { forrange p.tasks { fmt.Println("Consume Task", *task) } wg.Done() }() } wg.Wait() fmt.Println("WorkerPool | Pool exit.")}
Here is the test code
func Main () {tasknum: = projects: = make ( Chan *string , Tasknum) //start production task Goroutine go func () {for I: = 0 ;; i++ {s: = "Project" + FMT. Sprintf ( "%d" , i) fmt. Println ( "produce task" , s) projects <-&s time. Sleep (5 * time. Millisecond)}} () P: = workerpool{tasks:projects, poolsize: 10< /span>,} p.run ()}