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. // Returns the index of the least busy device, or -1 if all are too busy.
  25. func (m *deviceActivity) leastBusy(availability []Availability) int {
  26. m.mut.Lock()
  27. low := 2<<30 - 1
  28. best := -1
  29. for i := range availability {
  30. if usage := m.act[availability[i].ID]; usage < low {
  31. low = usage
  32. best = i
  33. }
  34. }
  35. m.mut.Unlock()
  36. return best
  37. }
  38. func (m *deviceActivity) using(availability Availability) {
  39. m.mut.Lock()
  40. m.act[availability.ID]++
  41. m.mut.Unlock()
  42. }
  43. func (m *deviceActivity) done(availability Availability) {
  44. m.mut.Lock()
  45. m.act[availability.ID]--
  46. m.mut.Unlock()
  47. }