sync_test.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. // Copyright (C) 2015 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. package sync
  7. import (
  8. "strings"
  9. "sync"
  10. "testing"
  11. "time"
  12. "github.com/syncthing/syncthing/lib/logger"
  13. )
  14. const (
  15. logThreshold = 100 * time.Millisecond
  16. shortWait = 5 * time.Millisecond
  17. longWait = 125 * time.Millisecond
  18. )
  19. func TestTypes(t *testing.T) {
  20. debug = false
  21. l.SetDebug("sync", false)
  22. if _, ok := NewMutex().(*sync.Mutex); !ok {
  23. t.Error("Wrong type")
  24. }
  25. if _, ok := NewRWMutex().(*sync.RWMutex); !ok {
  26. t.Error("Wrong type")
  27. }
  28. if _, ok := NewWaitGroup().(*sync.WaitGroup); !ok {
  29. t.Error("Wrong type")
  30. }
  31. debug = true
  32. l.SetDebug("sync", true)
  33. if _, ok := NewMutex().(*loggedMutex); !ok {
  34. t.Error("Wrong type")
  35. }
  36. if _, ok := NewRWMutex().(*loggedRWMutex); !ok {
  37. t.Error("Wrong type")
  38. }
  39. if _, ok := NewWaitGroup().(*loggedWaitGroup); !ok {
  40. t.Error("Wrong type")
  41. }
  42. debug = false
  43. l.SetDebug("sync", false)
  44. }
  45. func TestMutex(t *testing.T) {
  46. oldClock := timeNow
  47. clock := newTestClock()
  48. timeNow = clock.Now
  49. defer func() { timeNow = oldClock }()
  50. debug = true
  51. l.SetDebug("sync", true)
  52. threshold = logThreshold
  53. msgmut := sync.Mutex{}
  54. var messages []string
  55. l.AddHandler(logger.LevelDebug, func(_ logger.LogLevel, message string) {
  56. msgmut.Lock()
  57. messages = append(messages, message)
  58. msgmut.Unlock()
  59. })
  60. mut := NewMutex()
  61. mut.Lock()
  62. clock.wind(shortWait)
  63. mut.Unlock()
  64. if len(messages) > 0 {
  65. t.Errorf("Unexpected message count")
  66. }
  67. mut.Lock()
  68. clock.wind(longWait)
  69. mut.Unlock()
  70. if len(messages) != 1 {
  71. t.Errorf("Unexpected message count")
  72. }
  73. debug = false
  74. l.SetDebug("sync", false)
  75. }
  76. func TestRWMutex(t *testing.T) {
  77. oldClock := timeNow
  78. clock := newTestClock()
  79. timeNow = clock.Now
  80. defer func() { timeNow = oldClock }()
  81. debug = true
  82. l.SetDebug("sync", true)
  83. threshold = logThreshold
  84. msgmut := sync.Mutex{}
  85. var messages []string
  86. l.AddHandler(logger.LevelDebug, func(_ logger.LogLevel, message string) {
  87. msgmut.Lock()
  88. messages = append(messages, message)
  89. msgmut.Unlock()
  90. })
  91. mut := NewRWMutex()
  92. mut.Lock()
  93. clock.wind(shortWait)
  94. mut.Unlock()
  95. if len(messages) > 0 {
  96. t.Errorf("Unexpected message count")
  97. }
  98. mut.Lock()
  99. clock.wind(longWait)
  100. mut.Unlock()
  101. if len(messages) != 1 {
  102. t.Errorf("Unexpected message count")
  103. }
  104. // Testing rlocker logging
  105. wait := make(chan struct{})
  106. locking := make(chan struct{})
  107. mut.RLock()
  108. go func() {
  109. close(locking)
  110. mut.Lock()
  111. close(wait)
  112. }()
  113. <-locking
  114. clock.wind(longWait)
  115. mut.RUnlock()
  116. <-wait
  117. mut.Unlock()
  118. if len(messages) != 2 {
  119. t.Errorf("Unexpected message count")
  120. } else if !strings.Contains(messages[1], "RUnlockers while locking:\nat sync") || !strings.Contains(messages[1], "sync_test.go:") {
  121. t.Error("Unexpected message")
  122. }
  123. // Testing multiple rlockers
  124. mut.RLock()
  125. mut.RLock()
  126. mut.RLock()
  127. _ = 1 // skip empty critical section check
  128. mut.RUnlock()
  129. mut.RUnlock()
  130. mut.RUnlock()
  131. debug = false
  132. l.SetDebug("sync", false)
  133. }
  134. func TestWaitGroup(t *testing.T) {
  135. oldClock := timeNow
  136. clock := newTestClock()
  137. timeNow = clock.Now
  138. defer func() { timeNow = oldClock }()
  139. debug = true
  140. l.SetDebug("sync", true)
  141. threshold = logThreshold
  142. msgmut := sync.Mutex{}
  143. var messages []string
  144. l.AddHandler(logger.LevelDebug, func(_ logger.LogLevel, message string) {
  145. msgmut.Lock()
  146. messages = append(messages, message)
  147. msgmut.Unlock()
  148. })
  149. wg := NewWaitGroup()
  150. wg.Add(1)
  151. waiting := make(chan struct{})
  152. go func() {
  153. <-waiting
  154. clock.wind(shortWait)
  155. wg.Done()
  156. }()
  157. close(waiting)
  158. wg.Wait()
  159. if len(messages) > 0 {
  160. t.Errorf("Unexpected message count")
  161. }
  162. wg = NewWaitGroup()
  163. waiting = make(chan struct{})
  164. wg.Add(1)
  165. go func() {
  166. <-waiting
  167. clock.wind(longWait)
  168. wg.Done()
  169. }()
  170. close(waiting)
  171. wg.Wait()
  172. if len(messages) != 1 {
  173. t.Errorf("Unexpected message count")
  174. }
  175. debug = false
  176. l.SetDebug("sync", false)
  177. }
  178. func TestTimeoutCond(t *testing.T) {
  179. // WARNING this test relies heavily on threads not being stalled at particular points.
  180. // As such, it's pretty unstable on the build server. It has been left in as it still
  181. // exercises the deadlock detector, and one of the two things it tests is still functional.
  182. // See the comments in runLocks
  183. const (
  184. // Low values to avoid being intrusive in continuous testing. Can be
  185. // increased significantly for stress testing.
  186. iterations = 100
  187. routines = 10
  188. timeMult = 2
  189. )
  190. c := NewTimeoutCond(NewMutex())
  191. // Start a routine to periodically broadcast on the cond.
  192. go func() {
  193. d := time.Duration(routines) * timeMult * time.Millisecond / 2
  194. t.Log("Broadcasting every", d)
  195. for i := 0; i < iterations; i++ {
  196. time.Sleep(d)
  197. c.L.Lock()
  198. c.Broadcast()
  199. c.L.Unlock()
  200. }
  201. }()
  202. // Start several routines that wait on it with different timeouts.
  203. var results [routines][2]int
  204. var wg sync.WaitGroup
  205. for i := 0; i < routines; i++ {
  206. i := i
  207. wg.Add(1)
  208. go func() {
  209. d := time.Duration(i) * timeMult * time.Millisecond
  210. t.Logf("Routine %d waits for %v\n", i, d)
  211. succ, fail := runLocks(t, iterations, c, d)
  212. results[i][0] = succ
  213. results[i][1] = fail
  214. wg.Done()
  215. }()
  216. }
  217. wg.Wait()
  218. // Print a table of routine number: successes, failures.
  219. for i, v := range results {
  220. t.Logf("%4d: %4d %4d\n", i, v[0], v[1])
  221. }
  222. }
  223. func runLocks(t *testing.T, iterations int, c *TimeoutCond, d time.Duration) (succ, fail int) {
  224. for i := 0; i < iterations; i++ {
  225. c.L.Lock()
  226. // The thread may be stalled, so we can't test the 'succeeded late' case reliably.
  227. // Therefore make sure that we start t0 before starting the timeout, and only test
  228. // the 'failed early' case.
  229. t0 := time.Now()
  230. w := c.SetupWait(d)
  231. res := w.Wait()
  232. waited := time.Since(t0)
  233. // Allow 20% slide in either direction, and a five milliseconds of
  234. // scheduling delay... In tweaking these it was clear that things
  235. // worked like the should, so if this becomes a spurious failure
  236. // kind of thing feel free to remove or give significantly more
  237. // slack.
  238. if !res && waited < d*8/10 {
  239. t.Errorf("Wait failed early, %v < %v", waited, d)
  240. }
  241. if res && waited > d*11/10+5*time.Millisecond {
  242. // Ideally this would be t.Errorf
  243. t.Logf("WARNING: Wait succeeded late, %v > %v. This is probably a thread scheduling issue", waited, d)
  244. }
  245. w.Stop()
  246. if res {
  247. succ++
  248. } else {
  249. fail++
  250. }
  251. c.L.Unlock()
  252. }
  253. return
  254. }
  255. type testClock struct {
  256. time time.Time
  257. mut sync.Mutex
  258. }
  259. func newTestClock() *testClock {
  260. return &testClock{
  261. time: time.Now(),
  262. }
  263. }
  264. func (t *testClock) Now() time.Time {
  265. t.mut.Lock()
  266. now := t.time
  267. t.time = t.time.Add(time.Nanosecond)
  268. t.mut.Unlock()
  269. return now
  270. }
  271. func (t *testClock) wind(d time.Duration) {
  272. t.mut.Lock()
  273. t.time = t.time.Add(d)
  274. t.mut.Unlock()
  275. }