util.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // Copyright (C) 2014 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 model
  7. import (
  8. "fmt"
  9. "sync"
  10. "time"
  11. )
  12. type Holdable interface {
  13. Holders() string
  14. }
  15. func newDeadlockDetector(timeout time.Duration) *deadlockDetector {
  16. return &deadlockDetector{
  17. timeout: timeout,
  18. lockers: make(map[string]sync.Locker),
  19. }
  20. }
  21. type deadlockDetector struct {
  22. timeout time.Duration
  23. lockers map[string]sync.Locker
  24. }
  25. func (d *deadlockDetector) Watch(name string, mut sync.Locker) {
  26. d.lockers[name] = mut
  27. go func() {
  28. for {
  29. time.Sleep(d.timeout / 4)
  30. ok := make(chan bool, 2)
  31. go func() {
  32. mut.Lock()
  33. _ = 1 // empty critical section
  34. mut.Unlock()
  35. ok <- true
  36. }()
  37. go func() {
  38. time.Sleep(d.timeout)
  39. ok <- false
  40. }()
  41. if r := <-ok; !r {
  42. msg := fmt.Sprintf("deadlock detected at %s", name)
  43. for otherName, otherMut := range d.lockers {
  44. if otherHolder, ok := otherMut.(Holdable); ok {
  45. msg += "\n===" + otherName + "===\n" + otherHolder.Holders()
  46. }
  47. }
  48. panic(msg)
  49. }
  50. }
  51. }()
  52. }