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