Prevent time.Timer memory leak by using a singleton timer in bufferedPipes. Fix #137

pull/138/head
Andy Wang 4 years ago
parent 39c06a6e1d
commit 4baca256f7
No known key found for this signature in database
GPG Key ID: 181B49F9F38F3374

@ -20,11 +20,14 @@ type datagramBufferedPipe struct {
rwCond *sync.Cond
wtTimeout time.Duration
rDeadline time.Time
timer *time.Timer
}
func NewDatagramBufferedPipe() *datagramBufferedPipe {
d := &datagramBufferedPipe{
rwCond: sync.NewCond(&sync.Mutex{}),
timer: time.NewTimer(0),
}
return d
}
@ -45,7 +48,7 @@ func (d *datagramBufferedPipe) Read(target []byte) (int, error) {
if delta <= 0 {
return 0, ErrTimeout
}
time.AfterFunc(delta, d.rwCond.Broadcast)
d.broadcastAfter(delta)
}
if len(d.pLens) > 0 {
@ -81,12 +84,12 @@ func (d *datagramBufferedPipe) WriteTo(w io.Writer) (n int64, err error) {
}
if d.wtTimeout == 0 {
// if there hasn't been a scheduled broadcast
time.AfterFunc(delta, d.rwCond.Broadcast)
d.broadcastAfter(delta)
}
}
if d.wtTimeout != 0 {
d.rDeadline = time.Now().Add(d.wtTimeout)
time.AfterFunc(d.wtTimeout, d.rwCond.Broadcast)
d.broadcastAfter(d.wtTimeout)
}
if len(d.pLens) > 0 {
@ -160,3 +163,15 @@ func (d *datagramBufferedPipe) SetWriteToTimeout(t time.Duration) {
d.wtTimeout = t
d.rwCond.Broadcast()
}
func (d *datagramBufferedPipe) broadcastAfter(delta time.Duration) {
// d.rwCond.L must be held, otherwise the following timer operations will race
if !d.timer.Stop() {
<-d.timer.C
}
d.timer.Reset(delta)
go func() {
<-d.timer.C
d.rwCond.Broadcast()
}()
}

@ -18,11 +18,14 @@ type streamBufferedPipe struct {
rwCond *sync.Cond
rDeadline time.Time
wtTimeout time.Duration
timer *time.Timer
}
func NewStreamBufferedPipe() *streamBufferedPipe {
p := &streamBufferedPipe{
rwCond: sync.NewCond(&sync.Mutex{}),
timer: time.NewTimer(0),
}
return p
}
@ -42,7 +45,7 @@ func (p *streamBufferedPipe) Read(target []byte) (int, error) {
if d <= 0 {
return 0, ErrTimeout
}
time.AfterFunc(d, p.rwCond.Broadcast)
p.broadcastAfter(d)
}
if p.buf.Len() > 0 {
break
@ -72,12 +75,12 @@ func (p *streamBufferedPipe) WriteTo(w io.Writer) (n int64, err error) {
}
if p.wtTimeout == 0 {
// if there hasn't been a scheduled broadcast
time.AfterFunc(d, p.rwCond.Broadcast)
p.broadcastAfter(d)
}
}
if p.wtTimeout != 0 {
p.rDeadline = time.Now().Add(p.wtTimeout)
time.AfterFunc(p.wtTimeout, p.rwCond.Broadcast)
p.broadcastAfter(p.wtTimeout)
}
if p.buf.Len() > 0 {
written, er := p.buf.WriteTo(w)
@ -139,3 +142,15 @@ func (p *streamBufferedPipe) SetWriteToTimeout(d time.Duration) {
p.wtTimeout = d
p.rwCond.Broadcast()
}
func (p *streamBufferedPipe) broadcastAfter(d time.Duration) {
// p.rwCond.L must be held, otherwise the following timer operations will race
if !p.timer.Stop() {
<-p.timer.C
}
p.timer.Reset(d)
go func() {
<-p.timer.C
p.rwCond.Broadcast()
}()
}

Loading…
Cancel
Save