From adba57deda3017c35f859f8c1a5464d40feaaf8b Mon Sep 17 00:00:00 2001 From: Dmytro Vovk Date: Sat, 30 Nov 2024 10:20:08 +0000 Subject: [PATCH] fixed race --- client-stats.go | 2 +- client.go | 8 +++++--- torrent.go | 4 ++-- 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/client-stats.go b/client-stats.go index bfa6994e98..88f3031c39 100644 --- a/client-stats.go +++ b/client-stats.go @@ -40,7 +40,7 @@ type ClientStats struct { func (cl *Client) statsLocked() (stats ClientStats) { stats.ConnStats = cl.connStats.Copy() - stats.ActiveHalfOpenAttempts = cl.numHalfOpen + stats.ActiveHalfOpenAttempts = int(cl.numHalfOpen.Load()) stats.NumPeersUndialableWithoutHolepunch = len(cl.undialableWithoutHolepunch) stats.NumPeersUndialableWithoutHolepunchDialedAfterHolepunchConnect = len(cl.undialableWithoutHolepunchDialedAfterHolepunchConnect) diff --git a/client.go b/client.go index 72fa9be6c4..f2af7c6a1b 100644 --- a/client.go +++ b/client.go @@ -37,6 +37,8 @@ import ( gbtree "github.com/google/btree" "github.com/pion/datachannel" + "sync/atomic" + "github.com/anacrolix/torrent/bencode" "github.com/anacrolix/torrent/internal/check" "github.com/anacrolix/torrent/internal/limiter" @@ -84,7 +86,7 @@ type Client struct { pieceRequestOrder map[interface{}]*request_strategy.PieceRequestOrder acceptLimiter map[ipStr]int - numHalfOpen int + numHalfOpen atomic.Int64 websocketTrackers websocketTrackers @@ -691,8 +693,8 @@ func (cl *Client) noLongerHalfOpen(t *Torrent, addr string, attemptKey outgoingC panic("should exist") } path.Delete() - cl.numHalfOpen-- - if cl.numHalfOpen < 0 { + cl.numHalfOpen.Store(cl.numHalfOpen.Load() - 1) + if cl.numHalfOpen.Load() < 0 { panic("should not be possible") } for _, t := range cl.torrentsAsSlice() { diff --git a/torrent.go b/torrent.go index 47a097ebad..f5fce3ba16 100644 --- a/torrent.go +++ b/torrent.go @@ -1734,7 +1734,7 @@ func (t *Torrent) openNewConns(lock bool) (initiated int) { if len(t.cl.dialers) == 0 { return } - if t.cl.numHalfOpen >= t.cl.config.TotalHalfOpenConns { + if int(t.cl.numHalfOpen.Load()) >= t.cl.config.TotalHalfOpenConns { return } p := t.peers.PopMax() @@ -3108,7 +3108,7 @@ func (t *Torrent) addHalfOpen(addrStr string, attemptKey *PeerInfo, lock bool) { panic("should be unique") } path.Set(attemptKey) - t.cl.numHalfOpen++ + t.cl.numHalfOpen.Store(t.cl.numHalfOpen.Load() + 1) } // Start the process of connecting to the given peer for the given torrent if appropriate. I'm not