Skip to content

Commit

Permalink
netconn.go: Cleanup contexts on close
Browse files Browse the repository at this point in the history
Updates #255
  • Loading branch information
nhooyr committed Jan 9, 2021
1 parent 642a013 commit 482f584
Showing 1 changed file with 8 additions and 6 deletions.
14 changes: 8 additions & 6 deletions netconn.go
Expand Up @@ -50,16 +50,14 @@ func NetConn(ctx context.Context, c *Conn, msgType MessageType) net.Conn {
writeMu: newMu(c),
}

var writeCancel context.CancelFunc
nc.writeCtx, writeCancel = context.WithCancel(ctx)
var readCancel context.CancelFunc
nc.readCtx, readCancel = context.WithCancel(ctx)
nc.writeCtx, nc.writeCancel = context.WithCancel(ctx)
nc.readCtx, nc.readCancel = context.WithCancel(ctx)

nc.writeTimer = time.AfterFunc(math.MaxInt64, func() {
if !nc.writeMu.tryLock() {
// If the lock cannot be acquired, then there is an
// active write goroutine and so we should cancel the context.
writeCancel()
nc.writeCancel()
return
}
defer nc.writeMu.unlock()
Expand All @@ -75,7 +73,7 @@ func NetConn(ctx context.Context, c *Conn, msgType MessageType) net.Conn {
if !nc.readMu.tryLock() {
// If the lock cannot be acquired, then there is an
// active read goroutine and so we should cancel the context.
readCancel()
nc.readCancel()
return
}
defer nc.readMu.unlock()
Expand All @@ -98,11 +96,13 @@ type netConn struct {
writeMu *mu
writeExpired int64
writeCtx context.Context
writeCancel context.CancelFunc

readTimer *time.Timer
readMu *mu
readExpired int64
readCtx context.Context
readCancel context.CancelFunc
readEOFed bool
reader io.Reader
}
Expand All @@ -111,7 +111,9 @@ var _ net.Conn = &netConn{}

func (nc *netConn) Close() error {
nc.writeTimer.Stop()
nc.writeCancel()
nc.readTimer.Stop()
nc.readCancel()
return nc.c.Close(StatusNormalClosure, "")
}

Expand Down

0 comments on commit 482f584

Please sign in to comment.