From: Matt Joiner Date: Thu, 20 Mar 2014 11:01:56 +0000 (+1100) Subject: Fix races stopping clients and closing connections X-Git-Tag: v1.0.0~1769 X-Git-Url: http://www.git.stargrave.org/?a=commitdiff_plain;h=a07b53668f2a9026be0fb700862e02b95218b301;p=btrtrc.git Fix races stopping clients and closing connections --- diff --git a/client.go b/client.go index f7b5ebae..629b708b 100644 --- a/client.go +++ b/client.go @@ -539,6 +539,7 @@ func (cl *Client) stopped() bool { } func (me *Client) Stop() { + me.Lock() close(me.quit) me.event.Broadcast() for _, t := range me.torrents { @@ -546,6 +547,7 @@ func (me *Client) Stop() { c.Close() } } + me.Unlock() } func (cl *Client) acceptConnections() { @@ -679,7 +681,13 @@ func (me *Client) runConnection(sock net.Conn, torrent *Torrent) (err error) { write: make(chan []byte), post: make(chan encoding.BinaryMarshaler), } - defer conn.Close() + defer func() { + // There's a lock and deferred unlock later in this function. The + // client will not be locked when this deferred is invoked. + me.mu.Lock() + defer me.mu.Unlock() + conn.Close() + }() go conn.writer() go conn.writeOptimizer() conn.post <- peer_protocol.Bytes(peer_protocol.Protocol)