K
K
kvaks2022-04-14 17:33:34
go
kvaks, 2022-04-14 17:33:34

How to stop goroutines in GO pool worker?

Actually there is a good example of pool worker tell me how to stop all running goroutines?
I understand that to create another channel and close it, but it does not work.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
M
Maxim Fedorov, 2022-04-20
@kvaks

Modify the worker pool:
Inside each goroutine, listen ctx.Donefrom 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 // выход из горутины
      }
     }
}

R
Roman Kitaev, 2022-04-14
@deliro

Closing the jobs channel exits the for j := range jobs loop, the function ends, and the goroutine is killed. What's the question?

W
WinPooh32, 2022-04-15
@WinPooh32

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.

A
apelsinovi-sok, 2022-04-24
@apelsinovi-sok

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 question

Ask a Question

731 491 924 answers to any question