Skip to content

Commit

Permalink
Fix concurrent map read/write race condition
Browse files Browse the repository at this point in the history
  • Loading branch information
WithoutPants authored and anacrolix committed Jul 13, 2024
1 parent 8fa2e27 commit 552e7bf
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
5 changes: 5 additions & 0 deletions upnp/eventing.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"io"
"net/url"
"regexp"
"sync"
"time"

"github.com/anacrolix/log"
Expand Down Expand Up @@ -47,10 +48,14 @@ type subscriber struct {
// Intended to eventually be an embeddable implementation for managing
// eventing for a service. Not complete.
type Eventing struct {
mutex sync.Mutex
subscribers map[string]*subscriber
}

func (me *Eventing) Subscribe(callback []*url.URL, timeoutSeconds int) (sid string, actualTimeout int, err error) {
me.mutex.Lock()
defer me.mutex.Unlock()

var uuid [16]byte
io.ReadFull(rand.Reader, uuid[:])
sid = FormatUUID(uuid[:])
Expand Down
19 changes: 19 additions & 0 deletions upnp/eventing_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,3 +40,22 @@ func TestParseCallbackURLs(t *testing.T) {
t.Fatal(len(urls))
}
}

func TestSubscribeRace(t *testing.T) {
const n = 100

e := &Eventing{}
done := make(chan struct{})

doSubscribes := func() {
for i := 0; i < n; i++ {
e.Subscribe(nil, 10)
}
done <- struct{}{}
}

go doSubscribes()
go doSubscribes()
<-done
<-done
}

0 comments on commit 552e7bf

Please sign in to comment.