wireguard-go/device/pools.go

85 lines
1.9 KiB
Go
Raw Normal View History

2019-01-02 00:55:51 +00:00
/* SPDX-License-Identifier: MIT
2018-09-22 04:29:02 +00:00
*
* Copyright (C) 2017-2021 WireGuard LLC. All Rights Reserved.
2018-09-22 04:29:02 +00:00
*/
2019-03-03 03:04:41 +00:00
package device
2018-09-22 04:29:02 +00:00
import (
"sync"
"sync/atomic"
)
2018-09-22 04:29:02 +00:00
type WaitPool struct {
pool sync.Pool
cond sync.Cond
lock sync.Mutex
count uint32
max uint32
}
func NewWaitPool(max uint32, new func() interface{}) *WaitPool {
p := &WaitPool{pool: sync.Pool{New: new}, max: max}
p.cond = sync.Cond{L: &p.lock}
return p
}
func (p *WaitPool) Get() interface{} {
if p.max != 0 {
p.lock.Lock()
for atomic.LoadUint32(&p.count) >= p.max {
p.cond.Wait()
2018-09-22 04:29:02 +00:00
}
atomic.AddUint32(&p.count, 1)
p.lock.Unlock()
2018-09-22 04:29:02 +00:00
}
return p.pool.Get()
2018-09-22 04:29:02 +00:00
}
func (p *WaitPool) Put(x interface{}) {
p.pool.Put(x)
if p.max == 0 {
return
2018-09-22 04:29:02 +00:00
}
atomic.AddUint32(&p.count, ^uint32(0))
p.cond.Signal()
}
func (device *Device) PopulatePools() {
device.pool.messageBuffers = NewWaitPool(PreallocatedBuffersPerPool, func() interface{} {
return new([MaxMessageSize]byte)
})
device.pool.inboundElements = NewWaitPool(PreallocatedBuffersPerPool, func() interface{} {
return new(QueueInboundElement)
})
device.pool.outboundElements = NewWaitPool(PreallocatedBuffersPerPool, func() interface{} {
return new(QueueOutboundElement)
})
}
func (device *Device) GetMessageBuffer() *[MaxMessageSize]byte {
return device.pool.messageBuffers.Get().(*[MaxMessageSize]byte)
2018-09-22 04:29:02 +00:00
}
func (device *Device) PutMessageBuffer(msg *[MaxMessageSize]byte) {
device.pool.messageBuffers.Put(msg)
2018-09-22 04:29:02 +00:00
}
func (device *Device) GetInboundElement() *QueueInboundElement {
return device.pool.inboundElements.Get().(*QueueInboundElement)
2018-09-22 04:29:02 +00:00
}
func (device *Device) PutInboundElement(elem *QueueInboundElement) {
elem.clearPointers()
device.pool.inboundElements.Put(elem)
2018-09-22 04:29:02 +00:00
}
func (device *Device) GetOutboundElement() *QueueOutboundElement {
return device.pool.outboundElements.Get().(*QueueOutboundElement)
2018-09-22 04:29:02 +00:00
}
func (device *Device) PutOutboundElement(elem *QueueOutboundElement) {
elem.clearPointers()
device.pool.outboundElements.Put(elem)
2018-09-22 04:29:02 +00:00
}