I'm trying to understand how to process a queue in Go if the queue can grow from the processing function itself. See below code.
In this pseudo code, I want to limit the number of handlers I am making to 10. Therefore I create 10 handlers that process the queue. I then start the queue off with a url.
My issue is that according to the docs, the sender
to a channel will block until a receiver receives the data. In the below code, each process is a receiver that handles a new url. However it's quite easy to see that if a process sends 11 links to the queue, it will block until all receivers are finished handling these new links. If those receivers each have even 1 link, then they will also block while sending that new 1 link to the queue. Since everyone is blocked, nothing finishes.
I'm wondering what is the general solution in go, for processing a queue which can grow from the process itself. Note that I think I can do this with a lock on an array called queue
, but I'm trying to understand how it would be done with channels.
var queue = make(chan string)
func process(){
for currentURL := range queue {
links, _ := ... // some http call that gets links from a url
for _, link := links {
queue <- link
}
}
}
func main () {
for i :=0; i < 10; i++ {
go process()
}
queue <- "https://stackoverflow.com"
...
// block until receive some quit message
<-quit
}