deviceactivity.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // Copyright (C) 2014 Jakob Borg and Contributors (see the CONTRIBUTORS file).
  2. //
  3. // This program is free software: you can redistribute it and/or modify it
  4. // under the terms of the GNU General Public License as published by the Free
  5. // Software Foundation, either version 3 of the License, or (at your option)
  6. // any later version.
  7. //
  8. // This program is distributed in the hope that it will be useful, but WITHOUT
  9. // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  10. // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  11. // more details.
  12. //
  13. // You should have received a copy of the GNU General Public License along
  14. // with this program. If not, see <http://www.gnu.org/licenses/>.
  15. package model
  16. import (
  17. "sync"
  18. "github.com/syncthing/syncthing/internal/protocol"
  19. )
  20. // deviceActivity tracks the number of outstanding requests per device and can
  21. // answer which device is least busy. It is safe for use from multiple
  22. // goroutines.
  23. type deviceActivity struct {
  24. act map[protocol.DeviceID]int
  25. mut sync.Mutex
  26. }
  27. func newDeviceActivity() *deviceActivity {
  28. return &deviceActivity{
  29. act: make(map[protocol.DeviceID]int),
  30. }
  31. }
  32. func (m deviceActivity) leastBusy(availability []protocol.DeviceID) protocol.DeviceID {
  33. m.mut.Lock()
  34. var low int = 2<<30 - 1
  35. var selected protocol.DeviceID
  36. for _, device := range availability {
  37. if usage := m.act[device]; usage < low {
  38. low = usage
  39. selected = device
  40. }
  41. }
  42. m.mut.Unlock()
  43. return selected
  44. }
  45. func (m deviceActivity) using(device protocol.DeviceID) {
  46. m.mut.Lock()
  47. defer m.mut.Unlock()
  48. m.act[device]++
  49. }
  50. func (m deviceActivity) done(device protocol.DeviceID) {
  51. m.mut.Lock()
  52. defer m.mut.Unlock()
  53. m.act[device]--
  54. }