Golang worker Goroutine Pool model

Source: Internet
Author: User
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 ()}  

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.