Changeset 703 in code for trunk/conn.go


Ignore:
Timestamp:
Nov 17, 2021, 12:13:55 PM (4 years ago)
Author:
contact
Message:

Introduce conn.NewContext

This function wraps a parent context, and returns a new context
cancelled when the connection is closed. This will make it so
operations started from downstreamConn.handleMessage will be
cancelled when the connection is closed.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/conn.go

    r691 r703  
    173173        outgoing chan<- *irc.Message
    174174        closed   bool
     175        closedCh chan struct{}
    175176}
    176177
     
    182183                outgoing: outgoing,
    183184                logger:   options.Logger,
     185                closedCh: make(chan struct{}),
    184186        }
    185187
     
    238240        c.closed = true
    239241        close(c.outgoing)
     242        close(c.closedCh)
    240243        return err
    241244}
     
    278281        return c.conn.LocalAddr()
    279282}
     283
     284// NewContext returns a copy of the parent context with a new Done channel. The
     285// returned context's Done channel is closed when the connection is closed,
     286// when the returned cancel function is called, or when the parent context's
     287// Done channel is closed, whichever happens first.
     288//
     289// Canceling this context releases resources associated with it, so code should
     290// call cancel as soon as the operations running in this Context complete.
     291func (c *conn) NewContext(parent context.Context) (context.Context, context.CancelFunc) {
     292        ctx, cancel := context.WithCancel(parent)
     293
     294        go func() {
     295                defer cancel()
     296
     297                select {
     298                case <-ctx.Done():
     299                        // The parent context has been cancelled, or the caller has called
     300                        // cancel()
     301                case <-c.closedCh:
     302                        // The connection has been closed
     303                }
     304        }()
     305
     306        return ctx, cancel
     307}
Note: See TracChangeset for help on using the changeset viewer.