Skip to content

Commit

Permalink
adjust close wait group usage
Browse files Browse the repository at this point in the history
  • Loading branch information
mh0lt committed Aug 7, 2024
1 parent 3a56aa7 commit a984272
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 21 deletions.
10 changes: 8 additions & 2 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -449,8 +449,12 @@ func (cl *Client) Close() (errs []error) {
fmt.Println("CLI CLS")
var mu sync.Mutex
for _, t := range cl.torrentsAsSlice() {
closeGroup.Add(1)

go func(t *Torrent) {
err := t.close(&closeGroup)
defer closeGroup.Done()

err := t.close()
if err != nil {
mu.Lock()
errs = append(errs, err)
Expand Down Expand Up @@ -1535,7 +1539,9 @@ func (cl *Client) dropTorrent(infoHash metainfo.Hash, wg *sync.WaitGroup) (err e
err = fmt.Errorf("no such torrent")
return
}
err = t.close(wg)
wg.Add(1)
defer wg.Done()
err = t.close()
delete(cl.torrents, infoHash)
return
}
Expand Down
24 changes: 8 additions & 16 deletions torrent.go
Original file line number Diff line number Diff line change
Expand Up @@ -1065,7 +1065,7 @@ func (t *Torrent) numPiecesCompleted(lock bool) (num pieceIndex) {
return pieceIndex(t._completedPieces.GetCardinality())
}

func (t *Torrent) close(wg *sync.WaitGroup) (err error) {
func (t *Torrent) close() (err error) {
if !t.closed.Set() {
err = errors.New("already closed")
return
Expand Down Expand Up @@ -1099,23 +1099,15 @@ func (t *Torrent) close(wg *sync.WaitGroup) (err error) {
}()

if t.storage != nil {
closed := make(chan struct{})
defer func() { closed <- struct{}{} }()
fmt.Println("ST CLS", t.name(true))
wg.Add(1)
go func() {
defer wg.Done()
<-closed
t.storageLock.Lock()
defer t.storageLock.Unlock()
if f := t.storage.Close; f != nil {
fmt.Println("CLS", t.name(true))
if err := f(); err != nil {
fmt.Println("ERR", t.name(true))
t.logger.WithDefaultLevel(log.Warning).Printf("error closing storage: %v", err)
}
t.storageLock.Lock()
defer t.storageLock.Unlock()
if f := t.storage.Close; f != nil {
fmt.Println("CLS", t.name(true))
if err := f(); err != nil {
t.logger.WithDefaultLevel(log.Warning).Printf("error closing storage: %v", err)
}
}()
}
}

return
Expand Down
4 changes: 1 addition & 3 deletions torrent_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (
"net"
"os"
"path/filepath"
"sync"
"testing"

g "github.com/anacrolix/generics"
Expand Down Expand Up @@ -247,7 +246,6 @@ func TestRelativeAvailabilityHaveNone(t *testing.T) {
tt.onSetInfo(true, true)
err = pc.peerSentHaveNone(true)
c.Assert(err, qt.IsNil)
var wg sync.WaitGroup
tt.close(&wg)
tt.close()
tt.assertAllPiecesRelativeAvailabilityZero(true)
}

0 comments on commit a984272

Please sign in to comment.