util.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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 http://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. mut.Unlock()
  34. ok <- true
  35. }()
  36. go func() {
  37. time.Sleep(d.timeout)
  38. ok <- false
  39. }()
  40. if r := <-ok; !r {
  41. msg := fmt.Sprintf("deadlock detected at %s", name)
  42. for otherName, otherMut := range d.lockers {
  43. if otherHolder, ok := otherMut.(Holdable); ok {
  44. msg += "\n===" + otherName + "===\n" + otherHolder.Holders()
  45. }
  46. }
  47. panic(msg)
  48. }
  49. }
  50. }()
  51. }