-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
46 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
package main | ||
|
||
import ( | ||
"fmt" | ||
"math/rand" | ||
"time" | ||
) | ||
|
||
// identify the data race | ||
// fix the issue. | ||
|
||
func main() { | ||
start := time.Now() | ||
reset := make(chan bool) | ||
// var t *time.Timer | ||
t := time.AfterFunc(randomDuration(), func() { | ||
fmt.Println(time.Since(start)) | ||
reset <- true | ||
}) | ||
for time.Since(start) < 5*time.Second { | ||
<-reset | ||
t.Reset(randomDuration()) | ||
} | ||
} | ||
|
||
func randomDuration() time.Duration { | ||
return time.Duration(rand.Int63n(1e9)) | ||
} | ||
|
||
//---------------------------------------------------- | ||
// (main goroutine) -> t <- (time.AfterFunc goroutine) | ||
//---------------------------------------------------- | ||
// (working condition) | ||
// main goroutine.. | ||
// t = time.AfterFunc() // returns a timer.. | ||
|
||
// AfterFunc goroutine | ||
// t.Reset() // timer reset | ||
//---------------------------------------------------- | ||
// (race condition- random duration is very small) | ||
// AfterFunc goroutine | ||
// t.Reset() // t = nil | ||
|
||
// main goroutine.. | ||
// t = time.AfterFunc() | ||
//---------------------------------------------------- |