src-d / go-mysql-server

An extensible MySQL server implementation in Go.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

sleep function cannot be cancelled

ajnavarro opened this issue · comments

we are just calling to time.Sleep, and that cannot be canceled from the Context. Change sleep to make it cancellable.

Easy way to reproduce: select sleep(1000) and control-C.

This should do it:

// sleepContext sleeps for the specified duration or until ctx ends, and reports
// whether the sleep ended due to context cancellation.
func sleepContext(ctx context.Context, dur time.Duration) bool {
  select {
  case <-time.After(dur):
    return false
  case <-ctx.Done():
    return true
  }
}

Note that after the context ends the timer will run to completion before it will be GC'd. If that matters you can do something more explicit with time.NewTimer. But in general that is probably safe unless you start a lot of these and they run for a long time.

Already fixed, forgot to close this :)

Your solution is better since the fact that the After is of course interrupted if the ctx is Done went over me so I was dumbly doing smaller sleeps, I'm updating the PR, thanks!