This article explains how to implement a thread pool through code. The code (from https://gobyexample.com/) and comments are as follows:
Package Main Import"FMT"Import" Time" //This is the worker thread that handles the specific business logic, takes out the tasks in 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, and in practice we can dynamically increase or decrease the threads as needed. forW: =1; W <=3; w++{Go worker (W, Jobs, results)}//Close Channel after adding 9 tasks//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, multiple threads take turns processing 9 of tasks.
Through this example, we can learn to:
1, go in multi-threaded application development 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.
Go implementation thread pool