Last active
October 19, 2018 21:06
-
-
Save zengjie/ec6194c5f8d2b6eefc2e2a8340c29e7f to your computer and use it in GitHub Desktop.
racy use of timers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"time" | |
) | |
func main() { | |
done := make(chan struct{}) | |
for i := 0; i < 1000; i++ { | |
tm := time.NewTimer(1 * time.Millisecond) | |
go func() { | |
for { | |
tm.Reset(1 * time.Millisecond) | |
time.Sleep(1 * time.Millisecond) | |
} | |
}() | |
go func() { | |
for { | |
<-tm.C | |
tm.Reset(1 * time.Millisecond) // <- If we comment this line, no panic will happen. | |
} | |
}() | |
} | |
<-done | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"time" | |
) | |
func main() { | |
done := make(chan struct{}) | |
for i := 0; i < 10000; i++ { | |
tm := time.NewTimer(1 * time.Millisecond) | |
for j := 0; j < 2; j++ { | |
go func() { | |
for { | |
if !tm.Stop() { | |
select { | |
case <-tm.C: | |
default: | |
continue | |
} | |
} | |
tm.Reset(1 * time.Millisecond) | |
time.Sleep(1 * time.Millisecond) | |
} | |
}() | |
} | |
go func() { | |
for { | |
<-tm.C | |
tm.Reset(1 * time.Millisecond) | |
} | |
}() | |
} | |
<-done | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment