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 < ; 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 ...