I have an app which creates, every few seconds, a routine fetching the current price from an API. It then sends the response to Monitor routine for analysis. If the Monitor finds that the price has changed significantly, it sends a notification.
It works fine if the delay between each go routine is large. It doesn't, if it is small: "fatal error: all goroutines are asleep - deadlock!" gets triggered and the program crashes.
I'm guessing (?) that the deadlock is caused by either (1) the Monitor being flooded with new price information (and not managing to analyse them timely); or (2) the Main function being flooded by messages from the Monitor.
There is probably also some weakness in the fact that the Main function appends the new price to a slice, while the Monitor is iterating through it.
How can this be resolved? Reading other posts here I thought that the "select" statement would be the magic cure, but it doesn't seem to be...
func main() {
ec := make(chan entry, 10)
mce := make (chan entry, 10)
mcn := make(chan string, 10)
go monitor(mce, mcn)
for {
go fetchData(ec)
select {
// get entries
case newEntry := <- ec:
log = append(log, newEntry)
mce <- newEntry
default:
{}
}
//check if any notifications received
select {
case newMsg := <- mcn:
fmt.Println(newMsg)
default:
{}
}
delay()
}
}
func monitor(mce <-chan entry, mcn chan<- string) {
for {
newEntry = <- mce
for _, item := range log {
// here - do some analysis comparing the newEntry against previous entries
// (essentially to see if notification should be triggered)
}
if should_send_notification {
mcn <- msg
}
}
}
func fetchData(ec chan<- entry) {
// here some code fetching newEntry from APIs
// send the newEntry back to the main function
ec <- newEntry
}