Answer the question
In order to leave comments, you need to log in
Answer the question
In order to leave comments, you need to log in
Modify the worker pool:
Inside each goroutine, listen ctx.Done
from the context.context
, which you pass to each routine, in addition, create a cancel () function that you will call if you need ...
When this function is called, all goroutines will receive a notification in select and exit .
How the goroutine will look like: an infinite loop, inside the select on your channel with jobs and on ctx.Done(), if ctx.Done() did not come (it will be called, for example, by an error in other places), then the channel with jobs will be read, but if will come ctx.Done() , then do return
for {
select {
case job := <-jobs:
// work with job
case <-ctx.Done():
c.logger.Errorf("shutdown cancelled: %v", ctx.Err())
return // выход из горутины
}
}
}
Closing the jobs channel exits the for j := range jobs loop, the function ends, and the goroutine is killed. What's the question?
Goroutines cannot be stopped externally. That's what the language documentation says.
In your example, the only way to stop goroutine execution is to close the jobs channel.
As far as I know, goroutines are stopped either through context forwarding or through a channel
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question