Skip to content

Commit a71af25

Browse files
committed
time: warn about correct use of a Timer's Stop/Reset methods
Updates #14038 Fixes #14383 Change-Id: Icf6acb7c5d13ff1d3145084544c030a778482a38 Reviewed-on: https://go-review.googlesource.com/23575 Reviewed-by: Dmitry Vyukov <[email protected]> Reviewed-by: Ian Lance Taylor <[email protected]> Run-TryBot: Ian Lance Taylor <[email protected]> TryBot-Result: Gobot Gobot <[email protected]>
1 parent f9b4556 commit a71af25

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

src/time/sleep.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,14 @@ type Timer struct {
5454
// expired or been stopped.
5555
// Stop does not close the channel, to prevent a read from the channel succeeding
5656
// incorrectly.
57+
//
58+
// To prevent the timer firing after a call to Stop,
59+
// check the return value and drain the channel. For example:
60+
// if !t.Stop() {
61+
// <-t.C
62+
// }
63+
// This cannot be done concurrent to other receives from the Timer's
64+
// channel.
5765
func (t *Timer) Stop() bool {
5866
if t.r.f == nil {
5967
panic("time: Stop called on uninitialized Timer")
@@ -80,6 +88,20 @@ func NewTimer(d Duration) *Timer {
8088
// Reset changes the timer to expire after duration d.
8189
// It returns true if the timer had been active, false if the timer had
8290
// expired or been stopped.
91+
//
92+
// To reuse an active timer, always call its Stop method first and—if it had
93+
// expired—drain the value from its channel. For example:
94+
// if !t.Stop() {
95+
// <-t.C
96+
// }
97+
// t.Reset(d)
98+
// This should not be done concurrent to other receives from the Timer's
99+
// channel.
100+
//
101+
// Note that it is not possible to use Reset's return value correctly, as there
102+
// is a race condition between draining the channel and the new timer expiring.
103+
// Reset should always be used in concert with Stop, as described above.
104+
// The return value exists to preserve compatibility with existing programs.
83105
func (t *Timer) Reset(d Duration) bool {
84106
if t.r.f == nil {
85107
panic("time: Reset called on uninitialized Timer")

0 commit comments

Comments
 (0)