deviceactivity.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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. "github.com/syncthing/syncthing/lib/protocol"
  9. "github.com/syncthing/syncthing/lib/sync"
  10. )
  11. // deviceActivity tracks the number of outstanding requests per device and can
  12. // answer which device is least busy. It is safe for use from multiple
  13. // goroutines.
  14. type deviceActivity struct {
  15. act map[protocol.DeviceID]int
  16. mut sync.Mutex
  17. }
  18. func newDeviceActivity() *deviceActivity {
  19. return &deviceActivity{
  20. act: make(map[protocol.DeviceID]int),
  21. mut: sync.NewMutex(),
  22. }
  23. }
  24. func (m *deviceActivity) leastBusy(availability []Availability) (Availability, bool) {
  25. m.mut.Lock()
  26. low := 2<<30 - 1
  27. found := false
  28. var selected Availability
  29. for _, info := range availability {
  30. if usage := m.act[info.ID]; usage < low {
  31. low = usage
  32. selected = info
  33. found = true
  34. }
  35. }
  36. m.mut.Unlock()
  37. return selected, found
  38. }
  39. func (m *deviceActivity) using(availability Availability) {
  40. m.mut.Lock()
  41. m.act[availability.ID]++
  42. m.mut.Unlock()
  43. }
  44. func (m *deviceActivity) done(availability Availability) {
  45. m.mut.Lock()
  46. m.act[availability.ID]--
  47. m.mut.Unlock()
  48. }