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() {

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


I’ve also posted the question on the golang subreddit:

(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;

select {
  case <-t.C:

(Govardhan G D) #3

Thanks that works