I have a goroutine, let's call it goProcessor, which processes requests coming in from other goroutines.
goProcessor can only process one request at a time. If a requests, let's call it req2, comes in while goProcessor is still processing the previous req1 request, req2 has to be discarded and will be simply lost.
I have implemented such logic using an unbuffered channel and the select statement, but I am not sure whether there could be a simpler more elegant way to accomplish what I want. A simple example of my solution is this
var c = make(chan string)
func main() {
goRequest := func(request string, delay int) {
time.Sleep(time.Duration(delay) * time.Second)
fmt.Printf("Here I am request %v\n", request)
select {
case c <- request:
fmt.Printf("%v sent\n", request)
default:
fmt.Printf("%v discarded\n", request)
}
}
goProcessor := func() {
for {
msg := <-c
fmt.Println("received", msg)
time.Sleep(3 * time.Second)
fmt.Println("processed", msg)
}
}
go goRequest("First req", 1)
go goRequest("Second req", 2)
go goRequest("Third req", 5)
go goProcessor()
time.Sleep(10 * time.Second)
fmt.Println("Main has finished")
}