This article explains how to implement a thread pool with code. 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 the worker thread that handles the specific business logic, takes out the tasks in jobs, and places the processing results in the results.
Func worker (id int, jobs <-chan int, results chan <-int) {
For j: = 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 (chan int, 100)
Results: = make (chan int, 100)
With three threads open, that is, there are only 3 threads in the thread pool, and in practice we can dynamically increase or decrease threads as needed.
for w: = 1; W <= 3; W + + {
Go worker (W, jobs, results)
}
Close channel after adding 9 tasks
Channel to indicate that's all the work we have.
for j: = 1; J <= 9; J + + {
Jobs <-J
}
Close (jobs)
Get all the processing results
For a: = 1; A <= 9; A + + {
<-results
}
}
Output results:
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, multiple threads handle 9 tasks in turn.
Through this example, we can learn:
1, go in multi-threaded application development is very simple.
2, channel is a tool for data interaction between 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.