deviceactivity.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. "sync"
  9. "github.com/syncthing/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. func (m *deviceActivity) leastBusy(availability []protocol.DeviceID) protocol.DeviceID {
  24. m.mut.Lock()
  25. low := 2<<30 - 1
  26. var selected protocol.DeviceID
  27. for _, device := range availability {
  28. if usage := m.act[device]; usage < low {
  29. low = usage
  30. selected = device
  31. }
  32. }
  33. m.mut.Unlock()
  34. return selected
  35. }
  36. func (m *deviceActivity) using(device protocol.DeviceID) {
  37. m.mut.Lock()
  38. m.act[device]++
  39. m.mut.Unlock()
  40. }
  41. func (m *deviceActivity) done(device protocol.DeviceID) {
  42. m.mut.Lock()
  43. m.act[device]--
  44. m.mut.Unlock()
  45. }