syncthing/lib/model/deviceactivity.go

56 lines
1.3 KiB
Go
Raw Normal View History

2014-11-16 13:13:20 -07:00
// Copyright (C) 2014 The Syncthing Authors.
2014-09-29 12:43:32 -07:00
//
2015-03-07 13:36:35 -07:00
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at http://mozilla.org/MPL/2.0/.
package model
import (
2015-09-22 10:38:46 -07:00
"github.com/syncthing/syncthing/lib/protocol"
2015-08-06 02:29:25 -07:00
"github.com/syncthing/syncthing/lib/sync"
)
// deviceActivity tracks the number of outstanding requests per device and can
// answer which device is least busy. It is safe for use from multiple
// goroutines.
type deviceActivity struct {
act map[protocol.DeviceID]int
mut sync.Mutex
}
func newDeviceActivity() *deviceActivity {
return &deviceActivity{
act: make(map[protocol.DeviceID]int),
2015-04-22 15:54:31 -07:00
mut: sync.NewMutex(),
}
}
func (m *deviceActivity) leastBusy(availability []Availability) (Availability, bool) {
m.mut.Lock()
2014-12-08 08:36:15 -07:00
low := 2<<30 - 1
found := false
var selected Availability
for _, info := range availability {
if usage := m.act[info.ID]; usage < low {
low = usage
selected = info
found = true
}
}
m.mut.Unlock()
return selected, found
}
func (m *deviceActivity) using(availability Availability) {
m.mut.Lock()
m.act[availability.ID]++
m.mut.Unlock()
}
func (m *deviceActivity) done(availability Availability) {
m.mut.Lock()
m.act[availability.ID]--
m.mut.Unlock()
}