"time"
)
+const (
+ DeviceRoutineNumberPerCPU = 3
+)
+
type Device struct {
isUp AtomicBool // device is (going) up
isClosed AtomicBool // device is closed? (acting as guard)
// synchronized resources (locks acquired in order)
state struct {
+ stopping sync.WaitGroup
mutex sync.Mutex
changing AtomicBool
current bool
// start workers
- for i := 0; i < runtime.NumCPU(); i += 1 {
+ cpus := runtime.NumCPU()
+ device.state.stopping.Add(DeviceRoutineNumberPerCPU * cpus)
+ for i := 0; i < cpus; i += 1 {
go device.RoutineEncryption()
go device.RoutineDecryption()
go device.RoutineHandshake()
device.peers.keyMap = make(map[NoisePublicKey]*Peer)
}
+func (device *Device) FlushPacketQueues() {
+ for {
+ select {
+ case elem, ok := <-device.queue.decryption:
+ if ok {
+ elem.Drop()
+ }
+ case elem, ok := <-device.queue.encryption:
+ if ok {
+ elem.Drop()
+ }
+ case <-device.queue.handshake:
+ default:
+ return
+ }
+ }
+
+}
+
func (device *Device) Close() {
if device.isClosed.Swap(true) {
return
device.signal.stop.Broadcast()
+ device.state.stopping.Wait()
+ device.FlushPacketQueues()
+
device.RemoveAllPeers()
device.rate.limiter.Close()
logDebug := device.log.Debug
defer func() {
- for {
- select {
- case elem, ok := <-device.queue.decryption:
- if ok {
- elem.Drop()
- }
- default:
- goto out
- }
- }
- out:
+ device.state.stopping.Done()
logDebug.Println("Routine: decryption worker - stopped")
}()
logDebug.Println("Routine: decryption worker - started")
logDebug := device.log.Debug
defer func() {
- for {
- select {
- case <-device.queue.handshake:
- default:
- goto out
- }
- }
- out:
+ device.state.stopping.Done()
logDebug.Println("Routine: handshake worker - stopped")
}()
logDebug := device.log.Debug
defer func() {
- for {
- select {
- case elem, ok := <-device.queue.encryption:
- if ok {
- elem.Drop()
- }
- default:
- goto out
- }
- }
- out:
+ device.state.stopping.Done()
logDebug.Println("Routine: encryption worker - stopped")
}()