internal/net: make ParallelDialer closes un-used conn

So the connection can be reclaimed more quickly, reduce resources usage
of ctrld, improving the performance a bit on low capacity devices.
This commit is contained in:
Cuong Manh Le
2023-06-16 19:09:40 +07:00
committed by Cuong Manh Le
parent 41139b3343
commit 48b2031269

View File

@@ -110,6 +110,8 @@ func (d *ParallelDialer) DialContext(ctx context.Context, network string, addrs
ctx, cancel := context.WithCancel(ctx)
defer cancel()
done := make(chan struct{})
defer close(done)
ch := make(chan *parallelDialerResult, len(addrs))
var wg sync.WaitGroup
wg.Add(len(addrs))
@@ -122,7 +124,13 @@ func (d *ParallelDialer) DialContext(ctx context.Context, network string, addrs
go func(addr string) {
defer wg.Done()
conn, err := d.Dialer.DialContext(ctx, network, addr)
ch <- &parallelDialerResult{conn: conn, err: err}
select {
case ch <- &parallelDialerResult{conn: conn, err: err}:
case <-done:
if conn != nil {
conn.Close()
}
}
}(addr)
}
@@ -134,6 +142,5 @@ func (d *ParallelDialer) DialContext(ctx context.Context, network string, addrs
}
errs = append(errs, res.err)
}
return nil, errors.Join(errs...)
}