// Closes resources upon exit of a function or when some condition no longer holds // Arguments: // - exitChan: Signals the watchdog to exit // - closerChan: Signals the watchdog to add an io.Closer to the list of closers // - f: Defines the OK condition. When false, all current closers are closed func (t *Trade) watchdog(log bitwrk.Logger, exitChan <-chan bool, closerChan <-chan io.Closer, f func() bool) { closers := make([]io.Closer, 0, 1) for { select { case closer := <-closerChan: closers = append(closers, closer) case <-exitChan: // Exit from watchdog if surrounding function has terminated log.Print("Watchdog exiting by request") return default: } // Check if condition still holds t.condition.L.Lock() ok := f() t.condition.L.Unlock() if !ok { log.Printf("Watchdog: closing %v channels", len(closers)) for _, c := range closers { err := c.Close() if err != nil { log.Printf("Error closing channel: %v", err) } } closers = closers[:0] // clear list of current closers } time.Sleep(250 * time.Millisecond) } }