Go implementation thread pool

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

This article explains how to implement a thread pool through code. The code and comments are as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21st
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
Package Main

Import"FMT"
Import"Time"

//This is a worker thread that handles the specific business logic, pulls the task out of jobs, and then places the processing results in results.
Func worker(Idint,Jobs<-Chanint,Results Chan<-int) {
forJ:=Range jobs{
Fmt.Println("Worker",Id,"Processing Job",J)
Time.Sleep( Time.Second)
Results<-J* 2
}
}

Func Main() {

//Two channel, one for placing work items and one for storing processing results.
Jobs:=Make(Chanint, -)
Results:=Make(Chanint, -)

//Open three threads, that is, there are only 3 threads in the thread pool, in fact we can dynamically increase or decrease the threads as needed.
forW:= 1;W<= 3;W++ {
Go worker(W,Jobs,Results)
}

//Add 9 tasks and close channel
//channel to indicate that's all of the work we have.
forJ:= 1;J<= 9;J++ {
Jobs<-J
}
Close(Jobs)

//Get all the processing results
forA:= 1;A<= 9;A++ {
<-Results
}
}

Output Result:
Worker 1 Processing Job 1
Worker 2 Processing Job 2
Worker 3 Processing Job 3
Worker 1 Processing Job 4
Worker 3 Processing Job 5
Worker 2 Processing Job 6
Worker 1 Processing Job 7
Worker 2 Processing Job 8
Worker 3 Processing Job 9

As you can see from the

, multiple threads take turns processing 9 of tasks.
With this example, we can learn that:
1, the development of multithreaded applications in Go is very simple.
2, Channel is a powerful tool for data interaction among different threads. In the example above, the main thread writes data to jobs, and three worker threads fetch data from a channel at the same time.

Related Article

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.