@@ -35,6 +35,7 @@ type Muxer struct {
3535 sendMutex sync.Mutex
3636 startChan chan bool
3737 doneChan chan bool
38+ waitGroup sync.WaitGroup
3839 stopMutex sync.Mutex
3940 protocolSenders map [uint16 ]chan * Segment
4041 protocolReceivers map [uint16 ]chan * Segment
@@ -51,6 +52,7 @@ func New(conn net.Conn) *Muxer {
5152 protocolSenders : make (map [uint16 ]chan * Segment ),
5253 protocolReceivers : make (map [uint16 ]chan * Segment ),
5354 }
55+ m .waitGroup .Add (1 )
5456 go m .readLoop ()
5557 return m
5658}
@@ -78,6 +80,8 @@ func (m *Muxer) Stop() {
7880 }
7981 // Close doneChan to signify that we're shutting down
8082 close (m .doneChan )
83+ // Wait for other goroutines to shutdown
84+ m .waitGroup .Wait ()
8185 // Close protocol receive channels
8286 // We rely on the individual mini-protocols to close the sender channel
8387 for _ , recvChan := range m .protocolReceivers {
@@ -116,7 +120,9 @@ func (m *Muxer) RegisterProtocol(protocolId uint16) (chan *Segment, chan *Segmen
116120 m .protocolSenders [protocolId ] = senderChan
117121 m .protocolReceivers [protocolId ] = receiverChan
118122 // Start Goroutine to handle outbound messages
123+ m .waitGroup .Add (1 )
119124 go func () {
125+ defer m .waitGroup .Done ()
120126 for {
121127 select {
122128 case _ , ok := <- m .doneChan :
@@ -157,6 +163,7 @@ func (m *Muxer) Send(msg *Segment) error {
157163// readLoop waits for incoming data on the connection, parses the segment, and passes it to the appropriate
158164// protocol
159165func (m * Muxer ) readLoop () {
166+ defer m .waitGroup .Done ()
160167 started := false
161168 for {
162169 // Break out of read loop if we're shutting down
0 commit comments