Skip to content

Commit

Permalink
use a wait group for clean shutdown of the mdns resolver
Browse files Browse the repository at this point in the history
  • Loading branch information
marten-seemann committed Aug 18, 2021
1 parent 62ad319 commit 51ee1c2
Showing 1 changed file with 9 additions and 8 deletions.
17 changes: 9 additions & 8 deletions p2p/mdns/mdns.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,8 @@ type mdnsService struct {
// The context is canceled when Close() is called.
ctxCancel context.CancelFunc

resolverRunning chan struct{}
server *zeroconf.Server
resolverWG sync.WaitGroup
server *zeroconf.Server

mutex sync.Mutex
notifees []Notifee
Expand All @@ -55,10 +55,9 @@ func NewMdnsService(host host.Host, serviceName string) *mdnsService {
serviceName = ServiceName
}
s := &mdnsService{
ctxCancel: cancel,
resolverRunning: make(chan struct{}),
host: host,
serviceName: serviceName,
ctxCancel: cancel,
host: host,
serviceName: serviceName,
}
s.startServer()
s.startResolver(ctx)
Expand All @@ -70,7 +69,7 @@ func (s *mdnsService) Close() error {
if s.server != nil {
s.server.Shutdown()
}
<-s.resolverRunning
s.resolverWG.Wait()
return nil
}

Expand Down Expand Up @@ -152,8 +151,10 @@ func (s *mdnsService) startServer() error {
}

func (s *mdnsService) startResolver(ctx context.Context) {
s.resolverWG.Add(2)
entryChan := make(chan *zeroconf.ServiceEntry, 1000)
go func() {
defer s.resolverWG.Done()
for entry := range entryChan {
// We only care about the TXT records.
// Ignore A, AAAA and PTR.
Expand Down Expand Up @@ -185,7 +186,7 @@ func (s *mdnsService) startResolver(ctx context.Context) {
}
}()
go func() {
defer close(s.resolverRunning)
defer s.resolverWG.Done()
if err := zeroconf.Browse(ctx, s.serviceName, mdnsDomain, entryChan); err != nil {
log.Debugf("zeroconf browsing failed: %s", err)
}
Expand Down

0 comments on commit 51ee1c2

Please sign in to comment.