2014-11-16 20:13:20 +00:00
|
|
|
// Copyright (C) 2014 The Syncthing Authors.
|
2014-09-29 19:43:32 +00:00
|
|
|
//
|
|
|
|
// This program is free software: you can redistribute it and/or modify it
|
|
|
|
// under the terms of the GNU General Public License as published by the Free
|
|
|
|
// Software Foundation, either version 3 of the License, or (at your option)
|
|
|
|
// any later version.
|
|
|
|
//
|
|
|
|
// This program is distributed in the hope that it will be useful, but WITHOUT
|
|
|
|
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
|
|
|
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
|
|
|
// more details.
|
|
|
|
//
|
|
|
|
// You should have received a copy of the GNU General Public License along
|
|
|
|
// with this program. If not, see <http://www.gnu.org/licenses/>.
|
2014-09-28 11:00:38 +00:00
|
|
|
|
|
|
|
package model
|
|
|
|
|
|
|
|
import (
|
|
|
|
"sync"
|
|
|
|
|
2015-01-13 12:22:56 +00:00
|
|
|
"github.com/syncthing/protocol"
|
2014-09-28 11:00:38 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// 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),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-11-29 21:22:50 +00:00
|
|
|
func (m *deviceActivity) leastBusy(availability []protocol.DeviceID) protocol.DeviceID {
|
2014-09-28 11:00:38 +00:00
|
|
|
m.mut.Lock()
|
2014-12-08 15:36:15 +00:00
|
|
|
low := 2<<30 - 1
|
2014-09-28 11:00:38 +00:00
|
|
|
var selected protocol.DeviceID
|
|
|
|
for _, device := range availability {
|
|
|
|
if usage := m.act[device]; usage < low {
|
|
|
|
low = usage
|
|
|
|
selected = device
|
|
|
|
}
|
|
|
|
}
|
|
|
|
m.mut.Unlock()
|
|
|
|
return selected
|
|
|
|
}
|
|
|
|
|
2014-11-29 21:22:50 +00:00
|
|
|
func (m *deviceActivity) using(device protocol.DeviceID) {
|
2014-09-28 11:00:38 +00:00
|
|
|
m.mut.Lock()
|
|
|
|
m.act[device]++
|
2014-11-29 21:22:50 +00:00
|
|
|
m.mut.Unlock()
|
2014-09-28 11:00:38 +00:00
|
|
|
}
|
|
|
|
|
2014-11-29 21:22:50 +00:00
|
|
|
func (m *deviceActivity) done(device protocol.DeviceID) {
|
2014-09-28 11:00:38 +00:00
|
|
|
m.mut.Lock()
|
|
|
|
m.act[device]--
|
2014-11-29 21:22:50 +00:00
|
|
|
m.mut.Unlock()
|
2014-09-28 11:00:38 +00:00
|
|
|
}
|