Go uses Goroutine and channel to implement working pool

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.
Assuming that there is a set of tasks that need to be processed asynchronously and in a large amount, we need to open multiple workers at the same time to ensure that the task is processed faster without clogging the task. Other languages, may need to open a multi-process to complete, multi-process control, IO consumption and so on will be a need to pay attention to the problem, and these Go can help us easily solve.

General implementation points and processes:

    • Create 2 channels, messages for sending task messages, result for receiving message processing results
    • Create 3 Worker threads to receive and process task messages from the messages channel and return processing results through channel result
    • 10 tasks published via channel messages
    • Receive task processing results by channel result

Example code:

Package Mainimport ("FMT" "StrConv" "Math/rand" "Time") type Message struct {Id int Name string}func Main () {messages: = Make (chan Message, +) Result: = Made (chan error, 100)//Create task processing worker for I: = 0; I &lt ; 3; i + + {go worker (I, messages, result)} total: = 0//Publish task for k: = 1; K <= 10; K + + {messages <-message{id:k, Name: "Job" + StrConv. Itoa (k)} Total + = 1} close (Messages)//Receive task processing results for J: = 1; J <= Total; J + + {res: = <-result if res! = Nil {fmt. Println (Res.  Error ())}} close (result)}func worker (worker int, msg <-chan Message, result chan<-error) {//from channel Listen & Receive new task for job in Chan Message: = Range msg {FMT. Println ("Worker:", Worker, "msg:", job.) Id, ":", job. Name)//Simulate task execution time. Sleep (time. Second * time. Duration (Randint (1, 3))//return execution result via channel result <-nil}}func randint (min, Max int) int {rand. Seed (time. Now (). Unixnano ()) return min + rand. INTN (max-min+1)}
Original address: Https://shockerli.net/post/go ...

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.