This is a creation in
Article, where the information may have evolved or changed.
Golang has a good performance in asynchronous processing. Because Goroutines and channels are very easy to use and effective asynchronous processing means. Let's take a look at Golang's simple task queue
A task queue for "non-task queue"
There are times when we need to do asynchronous processing but do not need a task to the column, such problems we use Golang can be very simple implementation. As follows:
go process(job)
This is indeed a great choice for many scenarios, such as manipulating an HTTP request to wait for the result. However, in some relatively complex and high concurrency scenarios, you cannot simply use this method to implement asynchronous processing. At this point, you need a queue to manage the tasks that need to be handled, and to handle those tasks in a certain order.
The simplest task queue
Next, look at one of the simplest task queues and worker models.
func worker(jobChan <-chan Job) { forrange jobChan { process(job) }}// make a channel with a capacity of 100.make(chan100)// start the workergo worker(jobChan)// enqueue a jobjobChan <- job
The code creates a channel for a Job object with a capacity of 100. Then open a worker association to remove the task from the channel and execute it. The task's queued operation is to put a job object into the task channel.
Although there are just a few lines of code above, it has done a lot of work. We implemented a simple, thread-safe, concurrent, and reliable task queue.
Current limit
In the example above, we initialized a task channel with a capacity of 100.
// make a channel with a capacity of 100.make(chan100)
This means that the task's queue operation is simple, as follows:
// enqueue a jobjobChan <- job
In this way, when the job channel has been put into 100 tasks, the queue operation will be blocked until a task is done by the worker processing. This is usually not a good phenomenon, because we usually do not want the program to appear blocking wait. At this point, we usually want a timeout mechanism to tell the service caller that the current service is busy and try again later. My previous blog post-I read "Handling data requests by go for millions per minute" describes a similar current-limit strategy. The method is similar here, that is, when the queue is full, return 503, telling the caller that the service is busy. The code is as follows:
// TryEnqueue tries to enqueue a job to the given job channel. Returns true if// the operation was successful, and false if enqueuing would not have been// possible without blocking. Job is not enqueued in the latter case.func TryEnqueue(job Job, jobChan <-chanbool { select { case jobChan <- job: returntrue default: returnfalse }}
This way, when we try to join the team, if the queue fails, put back a false, so that we can then deal with this return value as follows:
ifchan) { "max capacity reached"503) return}
This allows for a simple flow-limiting operation. When the Jobchan is full, the program goes to default to return FALSE, informing the caller of the current server situation.
Close workers
To the above steps, the current limit can be solved, then we consider, how to gracefully close the workers? Assuming we decide not to insert the task into the task queue anymore, we want all the queued tasks to be done, and we can do it very simply:
close(jobChan)
Yes, that's the line of code that lets the task queue no longer receive new tasks (which can still be read from the channel), and if we want to execute an already existing task in the queue, we just need:
forrange jobChan {...}
All jobs that have been queued will normally be woker taken away from execution. However, there is actually a problem, that is, the main association will not wait for the workers to complete the work will exit. It does not know when workers will be able to handle the above tasks. You can run the following example:
package main ( "FMT" ) var jobchan chan span class= "DT" >int func worker (Jobchan <-chan int ) {for job: = range jobchan{fmt. Printf ( "Execute task%d \n , Job)}} func main () {Jobchan = make (chan int , 100 ) //queued for I: = 1 ; I <= 10 ; i++{Jobchan <-i} close (Jobchan) go worker (Jobcha N)}
Running the discovery, Woker cannot guarantee that the job in the channel has been executed and exited. So how do we solve this problem?
Wait for woker execution to complete
Use SYSC. Waitgroup:
PackageMainImport("FMT" "Sync")varJobchanChan intvarWG Sync. WaitgroupfuncWorker (Jobchan <-Chan int) {deferWg. Done () forJob: =Rangejobchan{FMT. Printf (the Execute task%d\ n", Job)}}funcMain () {Jobchan = Make(Chan int, -)//Queue forI: =1; I <=Ten; i++{Jobchan <-i} WG. ADD (1)Close(Jobchan)GoWorker (Jobchan) WG. Wait ()}
Using this method of synchronization between the threads, the association waits for the worker to finish executing the job before exiting. Operation Result:
123456789100
Is this perfect? In the design of the function, in order to prevent the association of suspended animation, we should set a time-out for the process.
Timeout settings
The above example is the WG. Wait () will wait until the WG. Done () is called. But if this operation is suspended and cannot be called, it will always wait. This is what we don't want to see, so we can set a timeout for him. Here's how:
PackageMainImport("FMT" "Sync" "Time")varJobchanChan intvarWG Sync. WaitgroupfuncWorker (Jobchan <-Chan int) {deferWg. Done () forJob: =RangeJobchan {fmt. Printf (the Execute task%d\ n", job) time. Sleep (1* Time. Second)}}funcMain () {Jobchan = Make(Chan int, -)//Queue forI: =1; I <=Ten; i++ {Jobchan <-i} WG. ADD (1)Close(Jobchan)GoWorker (Jobchan) Res: = Waittimeout (&WG,5*time. Second)ifres {FMT. Println ("Execution Complete exit") }Else{FMT. Println ("Execution timeout exit") }}//timeout mechanismfuncWaittimeout (WG *sync. Waitgroup, timeout time. Duration)BOOL{ch: = Make(Chan struct{})Go func() {WG. Wait ()Close(CH)} ()Select{ Case<-ch:return true Case<-time. After (timeout):return false}}
The results of the implementation are as follows:
123450
In this way, the 5s timeout takes effect, although not all tasks are executed and will exit due to timeouts.
Sometimes we want Woker to discard the work being done, that is, the cancel operation, what to do with it?
Cancel Worker
We can use the context. Context implementation. As follows:
PackageMainImport("Context" "FMT" "Sync" "Time")varJobchanChan intvarCTX context. ContextvarCancel context. CancelfuncfuncWorker (Jobchan <-Chan int, CTX context. Context) { for{Select{ Case<-ctx. Done ():return CaseJob: = <-jobchan:fmt. Printf (the Execute task%d\ n", job) time. Sleep (1* Time. Second)}}}funcMain () {Jobchan = Make(Chan int, -)//Contex with cancel functionCTX, Cancel = context. Withcancel (context. Background ())//Queue forI: =1; I <=Ten; i++ {Jobchan <-i}Close(Jobchan)GoWorker (Jobchan, CTX) time. Sleep (2* Time. Second)//Adjust cancelCancel ()}
The results are as follows:
120
As can be seen, we wait for 2s, we actively call the cancellation operation, Woker the active exit.
This is the use of the context package to implement the cancellation operation, in essence, also listen to a channel operation, then we can not use the context to implement the cancellation operation?
Do not use the context timeout mechanism to implement cancellation:
PackageMainImport("FMT" "Time")varJobchanChan intfuncWorker (Jobchan <-Chan int, Cancelchan <-Chan struct{}) { for{Select{ Case<-cancelchan:return CaseJob: = <-jobchan:fmt. Printf (the Execute task%d\ n", job) time. Sleep (1* Time. Second)}}}funcMain () {Jobchan = Make(Chan int, -)//Cancel operation via ChanCancelchan: = Make(Chan struct{})//Queue forI: =1; I <=Ten; i++ {Jobchan <-i}Close(Jobchan)GoWorker (Jobchan, Cancelchan) time. Sleep (2* Time. Second)//Close Chan Close(Cancelchan)}
In this way, we use a signal to close Chan to implement the cancel operation. The reason is that the unbuffered Chan read is blocked, and when it is closed, it can be read to empty, so the return in select is executed.
Summarize
As a routine summary, this paper introduces some methods of synchronization and communication between Golang and the simplest implementation of task queue. As for the implementation of the worker pool, I wrote it in the other blog posts, and I don't write much here. This article is more tool-based code, writing functions can be borrowed, such as timeouts, cancellations, Chan's operation and so on.