The right way to restart time.Timer


(Govardhan G D) #1

Hello! I am using time.Timer in my code. There is one goroutine which is waiting for the Timer to expire. I have another goroutine which wants to restart the above timer under certain conditions. When the timer is restarted, the timer may or may not be expired yet. The first goroutine (which is waiting for the timer to expire), also restarts the timer on expiration. What is the effective way to do this, without any race conditions or deadlocks?

BTW, I did try the method explained in the docs:

if !t.Stop() {
    <-t.C
}
t.Reset(d)

But I’ve observed line 2 (draining out the channel) blocking in some cases.

Thanks

I’ve also posted the question on the golang subreddit: https://www.reddit.com/r/golang/comments/f16kqy/the_right_way_to_restart_timetimer/


(Jakob Borg) #2

The return from Stop() just says if the timer had expired, not whether someone else has already read from the channel or not. In your case you can’t be sure if the other routine has already done so or not. I would try a nonblocking read;

t.Stop()
select {
  case <-t.C:
  default:
}
t.Reset(d)

(Govardhan G D) #3

Thanks that works