]> Sergey Matveev's repositories - btrtrc.git/commitdiff
Fix race running and closing webtorrent tracker clients
authorMatt Joiner <anacrolix@gmail.com>
Mon, 25 Oct 2021 05:15:42 +0000 (16:15 +1100)
committerMatt Joiner <anacrolix@gmail.com>
Mon, 25 Oct 2021 05:15:42 +0000 (16:15 +1100)
webtorrent/tracker_client.go
wstracker.go

index 7972fb08beb7ca751762bd932c9b0e88364447cb..e6908c74235d443a7aead91227c16047ff7f751a 100644 (file)
@@ -106,9 +106,18 @@ func (tc *TrackerClient) doWebsocket() error {
        return err
 }
 
-func (tc *TrackerClient) Run() error {
+// Finishes initialization and spawns the run routine, calling onStop when it completes with the
+// result. We don't let the caller just spawn the runner directly, since then we can race against
+// .Close to finish initialization.
+func (tc *TrackerClient) Start(onStop func(error)) {
        tc.pingTicker = time.NewTicker(60 * time.Second)
        tc.cond.L = &tc.mu
+       go func() {
+               onStop(tc.run())
+       }()
+}
+
+func (tc *TrackerClient) run() error {
        tc.mu.Lock()
        for !tc.closed {
                tc.mu.Unlock()
index 4e83ca5fe790c793d8497e271997f83282ca6ade..f93f784a7f3c87c0bdc458d2d5f3fef38b4e29df 100644 (file)
@@ -55,12 +55,11 @@ func (me *websocketTrackers) Get(url string) (*webtorrent.TrackerClient, func())
                                }),
                        },
                }
-               go func() {
-                       err := value.TrackerClient.Run()
+               value.TrackerClient.Start(func(err error) {
                        if err != nil {
                                me.Logger.Printf("error running tracker client for %q: %v", url, err)
                        }
-               }()
+               })
                if me.clients == nil {
                        me.clients = make(map[string]*refCountedWebtorrentTrackerClient)
                }