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 := defaultClock
  47. clock := newTestClock()
  48. defaultClock = clock
  49. defer func() { defaultClock = 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 := defaultClock
  78. clock := newTestClock()
  79. defaultClock = clock
  80. defer func() { defaultClock = 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. }
  121. if !strings.Contains(messages[1], "RUnlockers while locking:\nat sync") || !strings.Contains(messages[1], "sync_test.go:") {
  122. t.Error("Unexpected message")
  123. }
  124. // Testing multiple rlockers
  125. mut.RLock()
  126. mut.RLock()
  127. mut.RLock()
  128. _ = 1 // skip empty critical section check
  129. mut.RUnlock()
  130. mut.RUnlock()
  131. mut.RUnlock()
  132. debug = false
  133. l.SetDebug("sync", false)
  134. }
  135. func TestWaitGroup(t *testing.T) {
  136. oldClock := defaultClock
  137. clock := newTestClock()
  138. defaultClock = clock
  139. defer func() { defaultClock = oldClock }()
  140. debug = true
  141. l.SetDebug("sync", true)
  142. threshold = logThreshold
  143. msgmut := sync.Mutex{}
  144. var messages []string
  145. l.AddHandler(logger.LevelDebug, func(_ logger.LogLevel, message string) {
  146. msgmut.Lock()
  147. messages = append(messages, message)
  148. msgmut.Unlock()
  149. })
  150. wg := NewWaitGroup()
  151. wg.Add(1)
  152. waiting := make(chan struct{})
  153. go func() {
  154. <-waiting
  155. clock.wind(shortWait)
  156. wg.Done()
  157. }()
  158. close(waiting)
  159. wg.Wait()
  160. if len(messages) > 0 {
  161. t.Errorf("Unexpected message count")
  162. }
  163. wg = NewWaitGroup()
  164. waiting = make(chan struct{})
  165. wg.Add(1)
  166. go func() {
  167. <-waiting
  168. clock.wind(longWait)
  169. wg.Done()
  170. }()
  171. close(waiting)
  172. wg.Wait()
  173. if len(messages) != 1 {
  174. t.Errorf("Unexpected message count")
  175. }
  176. debug = false
  177. l.SetDebug("sync", false)
  178. }
  179. func TestTimeoutCond(t *testing.T) {
  180. // WARNING this test relies heavily on threads not being stalled at particular points.
  181. // As such, it's pretty unstable on the build server. It has been left in as it still
  182. // exercises the deadlock detector, and one of the two things it tests is still functional.
  183. // See the comments in runLocks
  184. const (
  185. // Low values to avoid being intrusive in continuous testing. Can be
  186. // increased significantly for stress testing.
  187. iterations = 100
  188. routines = 10
  189. timeMult = 2
  190. )
  191. c := NewTimeoutCond(NewMutex())
  192. // Start a routine to periodically broadcast on the cond.
  193. go func() {
  194. d := time.Duration(routines) * timeMult * time.Millisecond / 2
  195. t.Log("Broadcasting every", d)
  196. for i := 0; i < iterations; i++ {
  197. time.Sleep(d)
  198. c.L.Lock()
  199. c.Broadcast()
  200. c.L.Unlock()
  201. }
  202. }()
  203. // Start several routines that wait on it with different timeouts.
  204. var results [routines][2]int
  205. var wg sync.WaitGroup
  206. for i := 0; i < routines; i++ {
  207. i := i
  208. wg.Add(1)
  209. go func() {
  210. d := time.Duration(i) * timeMult * time.Millisecond
  211. t.Logf("Routine %d waits for %v\n", i, d)
  212. succ, fail := runLocks(t, iterations, c, d)
  213. results[i][0] = succ
  214. results[i][1] = fail
  215. wg.Done()
  216. }()
  217. }
  218. wg.Wait()
  219. // Print a table of routine number: successes, failures.
  220. for i, v := range results {
  221. t.Logf("%4d: %4d %4d\n", i, v[0], v[1])
  222. }
  223. }
  224. func runLocks(t *testing.T, iterations int, c *TimeoutCond, d time.Duration) (succ, fail int) {
  225. for i := 0; i < iterations; i++ {
  226. c.L.Lock()
  227. // The thread may be stalled, so we can't test the 'succeeded late' case reliably.
  228. // Therefore make sure that we start t0 before starting the timeout, and only test
  229. // the 'failed early' case.
  230. t0 := time.Now()
  231. w := c.SetupWait(d)
  232. res := w.Wait()
  233. waited := time.Since(t0)
  234. // Allow 20% slide in either direction, and a five milliseconds of
  235. // scheduling delay... In tweaking these it was clear that things
  236. // worked like the should, so if this becomes a spurious failure
  237. // kind of thing feel free to remove or give significantly more
  238. // slack.
  239. if !res && waited < d*8/10 {
  240. t.Errorf("Wait failed early, %v < %v", waited, d)
  241. }
  242. if res && waited > d*11/10+5*time.Millisecond {
  243. // Ideally this would be t.Errorf
  244. t.Logf("WARNING: Wait succeeded late, %v > %v. This is probably a thread scheduling issue", waited, d)
  245. }
  246. w.Stop()
  247. if res {
  248. succ++
  249. } else {
  250. fail++
  251. }
  252. c.L.Unlock()
  253. }
  254. return
  255. }
  256. type testClock struct {
  257. time time.Time
  258. mut sync.Mutex
  259. }
  260. func newTestClock() *testClock {
  261. return &testClock{
  262. time: time.Now(),
  263. }
  264. }
  265. func (t *testClock) Now() time.Time {
  266. t.mut.Lock()
  267. now := t.time
  268. t.time = t.time.Add(time.Nanosecond)
  269. t.mut.Unlock()
  270. return now
  271. }
  272. func (t *testClock) wind(d time.Duration) {
  273. t.mut.Lock()
  274. t.time = t.time.Add(d)
  275. t.mut.Unlock()
  276. }