Advertisement
Guest User

Untitled

a guest
Jan 24th, 2017
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.77 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4. "flag"
  5. "fmt"
  6. "sync"
  7. "time"
  8. )
  9.  
  10. var withLock = flag.Bool("lock", false, "use lock on resets")
  11. var withStop = flag.Bool("stop", false, "use stop and channel drain on resets")
  12.  
  13. func main() {
  14. flag.Parse()
  15. fmt.Printf("lock: %v; stop: %v\n", *withLock, *withStop)
  16. var (
  17. resetGoroutines sync.WaitGroup
  18. timers sync.WaitGroup
  19. delays sync.WaitGroup
  20. )
  21. var (
  22. startReset = make(chan struct{})
  23. stopReset = make(chan struct{})
  24. )
  25. const (
  26. timersCount = 4
  27. resetGoroutinesCount = 32
  28. resetTo = time.Millisecond * 600
  29. resetInterval = resetTo / 6
  30. )
  31.  
  32. timers.Add(timersCount)
  33. delays.Add(timersCount)
  34.  
  35. for i := 0; i < timersCount; i++ {
  36. go func(x int) {
  37. tm := time.AfterFunc(time.Hour, func() {
  38. fmt.Printf("timer #%d fired\n", x)
  39. delays.Done()
  40. })
  41.  
  42. timers.Done()
  43.  
  44. var mu sync.Mutex
  45.  
  46. resetGoroutines.Add(resetGoroutinesCount)
  47.  
  48. for i := 0; i < resetGoroutinesCount; i++ {
  49. go func(i int) {
  50. defer resetGoroutines.Done()
  51.  
  52. <-startReset
  53.  
  54. tick := time.NewTicker(resetInterval)
  55. for {
  56. select {
  57. case <-tick.C:
  58. if *withLock {
  59. mu.Lock()
  60. }
  61. if *withStop {
  62. if !tm.Stop() {
  63. select {
  64. case <-tm.C:
  65. default:
  66. }
  67. }
  68. }
  69.  
  70. tm.Reset(resetTo)
  71.  
  72. if *withLock {
  73. mu.Unlock()
  74. }
  75. case <-stopReset:
  76. return
  77. }
  78. }
  79. }(i)
  80. }
  81. }(i)
  82. }
  83.  
  84. timers.Wait()
  85. fmt.Printf("initialized %d timers\n", timersCount)
  86. close(startReset)
  87.  
  88. fmt.Printf("will sleep for %s x 4 (delay which is set during resets)\n", resetTo)
  89. time.Sleep(resetTo * 4)
  90. close(stopReset)
  91. fmt.Println("done, waiting...")
  92.  
  93. resetGoroutines.Wait()
  94. fmt.Println("reset goroutines are done")
  95. delays.Wait()
  96. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement