deviceactivity.go 1.2 KB

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