Skip to content

Instantly share code, notes, and snippets.

@zengjie
Last active October 19, 2018 21:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zengjie/ec6194c5f8d2b6eefc2e2a8340c29e7f to your computer and use it in GitHub Desktop.
Save zengjie/ec6194c5f8d2b6eefc2e2a8340c29e7f to your computer and use it in GitHub Desktop.
racy use of timers
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
}
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