Skip to content

Commit c999108

Browse files
committed
time: revise Timer comments for Stop, Reset
The comments added for Go 1.7 are very close. Make explicit that they only apply if the timer is not known to have expired already. Fixes #14038. Change-Id: I6a38be7b2015e1571fc477e18444a8cee38aab29 Reviewed-on: https://go-review.googlesource.com/31350 Reviewed-by: Ian Lance Taylor <[email protected]> Reviewed-by: Brad Fitzpatrick <[email protected]>
1 parent 427674f commit c999108

File tree

1 file changed

+14
-4
lines changed

1 file changed

+14
-4
lines changed

src/time/sleep.go

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -56,10 +56,13 @@ type Timer struct {
5656
// incorrectly.
5757
//
5858
// To prevent the timer firing after a call to Stop,
59-
// check the return value and drain the channel. For example:
59+
// check the return value and drain the channel.
60+
// For example, assuming the program has not received from t.C already:
61+
//
6062
// if !t.Stop() {
6163
// <-t.C
6264
// }
65+
//
6366
// This cannot be done concurrent to other receives from the Timer's
6467
// channel.
6568
func (t *Timer) Stop() bool {
@@ -89,18 +92,25 @@ func NewTimer(d Duration) *Timer {
8992
// It returns true if the timer had been active, false if the timer had
9093
// expired or been stopped.
9194
//
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:
95+
// Resetting a timer must take care not to race with the send into t.C
96+
// that happens when the current timer expires.
97+
// If a program has already received a value from t.C, the timer is known
98+
// to have expired, and t.Reset can be used directly.
99+
// If a program has not yet received a value from t.C, however,
100+
// the timer must be stopped and—if Stop reports that the timer expired
101+
// before being stopped—the channel explicitly drained:
102+
//
94103
// if !t.Stop() {
95104
// <-t.C
96105
// }
97106
// t.Reset(d)
107+
//
98108
// This should not be done concurrent to other receives from the Timer's
99109
// channel.
100110
//
101111
// Note that it is not possible to use Reset's return value correctly, as there
102112
// 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.
113+
// Reset should always be invoked on stopped or expired channels, as described above.
104114
// The return value exists to preserve compatibility with existing programs.
105115
func (t *Timer) Reset(d Duration) bool {
106116
if t.r.f == nil {

0 commit comments

Comments
 (0)