client.go | 8 ++------ connection.go | 23 +++++++---------------- torrent.go | 4 +--- diff --git a/client.go b/client.go index ed81c0c993568bc518aaf105f697d4a2db77885c..2daff28265c416fb5cf8360e635c052cfbfe5bfd 100644 --- a/client.go +++ b/client.go @@ -1391,10 +1391,8 @@ err := decoder.Decode(&msg) receivedMessageTypes.Add(strconv.FormatInt(int64(msg.Type), 10), 1) me.mu.Lock() c.lastMessageReceived = time.Now() - select { - case <-c.closing: + if c.closed.IsSet() { return nil - default: } if err != nil { if me.stopped() || err == io.EOF { @@ -1691,10 +1689,8 @@ }) } func (cl *Client) usefulConn(t *torrent, c *connection) bool { - select { - case <-c.closing: + if c.closed.IsSet() { return false - default: } if !t.haveInfo() { return c.supportsExtension("ut_metadata") diff --git a/connection.go b/connection.go index f4fa461aa0e5af2b3aa8e4cdd1b746e2056dc559..fd28df3c850fdac9b197848a768896c1c072be50 100644 --- a/connection.go +++ b/connection.go @@ -10,9 +10,9 @@ "expvar" "fmt" "io" "net" - "sync" "time" + "github.com/anacrolix/missinggo" "github.com/anacrolix/torrent/bencode" pp "github.com/anacrolix/torrent/peer_protocol" ) @@ -36,8 +36,7 @@ rw io.ReadWriter // The real slim shady encrypted bool Discovery peerSource uTP bool - closing chan struct{} - mu sync.Mutex // Only for closing. + closed missinggo.Event post chan pp.Message writeCh chan []byte @@ -84,7 +83,6 @@ Choked: true, PeerChoked: true, PeerMaxRequests: 250, - closing: make(chan struct{}), writeCh: make(chan []byte), post: make(chan pp.Message), } @@ -235,14 +233,7 @@ ) } func (c *connection) Close() { - c.mu.Lock() - defer c.mu.Unlock() - select { - case <-c.closing: - return - default: - } - close(c.closing) + c.closed.Set() // TODO: This call blocks sometimes, why? go c.conn.Close() } @@ -260,7 +251,7 @@ func (c *connection) Post(msg pp.Message) { select { case c.post <- msg: - case <-c.closing: + case <-c.closed.C(): } } @@ -422,7 +413,7 @@ if err != nil { conn.Close() return } - case <-conn.closing: + case <-conn.closed.C(): return } } else { @@ -439,7 +430,7 @@ if err != nil { conn.Close() return } - case <-conn.closing: + case <-conn.closed.C(): return default: connectionWriterFlush.Add(1) @@ -505,7 +496,7 @@ lastWrite = time.Now() if pending.Len() == 0 { timer.Reset(keepAliveDelay) } - case <-conn.closing: + case <-conn.closed.C(): return } } diff --git a/torrent.go b/torrent.go index dcd78b8204347256a11615b20dff8124e8ef2fd3..214fc1af4ebd4209610f705460c2f8427119d454 100644 --- a/torrent.go +++ b/torrent.go @@ -146,9 +146,7 @@ t: t, cl: cl, } for _, c := range t.Conns { - select { - case <-c.closing: - default: + if !c.closed.IsSet() { wcs.c = append(wcs.c, c) } }