nodeactivity.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // Copyright (C) 2014 Jakob Borg and Contributors (see the CONTRIBUTORS file).
  2. // All rights reserved. Use of this source code is governed by an MIT-style
  3. // license that can be found in the LICENSE file.
  4. package model
  5. import (
  6. "sync"
  7. "github.com/syncthing/syncthing/internal/protocol"
  8. )
  9. // nodeActivity tracks the number of outstanding requests per node and can
  10. // answer which node is least busy. It is safe for use from multiple
  11. // goroutines.
  12. type nodeActivity struct {
  13. act map[protocol.NodeID]int
  14. mut sync.Mutex
  15. }
  16. func newNodeActivity() *nodeActivity {
  17. return &nodeActivity{
  18. act: make(map[protocol.NodeID]int),
  19. }
  20. }
  21. func (m nodeActivity) leastBusy(availability []protocol.NodeID) protocol.NodeID {
  22. m.mut.Lock()
  23. var low int = 2<<30 - 1
  24. var selected protocol.NodeID
  25. for _, node := range availability {
  26. if usage := m.act[node]; usage < low {
  27. low = usage
  28. selected = node
  29. }
  30. }
  31. m.mut.Unlock()
  32. return selected
  33. }
  34. func (m nodeActivity) using(node protocol.NodeID) {
  35. m.mut.Lock()
  36. defer m.mut.Unlock()
  37. m.act[node]++
  38. }
  39. func (m nodeActivity) done(node protocol.NodeID) {
  40. m.mut.Lock()
  41. defer m.mut.Unlock()
  42. m.act[node]--
  43. }