Safely close the quit channel

Prevent accidental closure of an already closed channel.

Signed-off-by: Gabriel Adrian Samfira <gsamfira@cloudbasesolutions.com>
This commit is contained in:
Gabriel Adrian Samfira 2024-01-06 14:15:52 +00:00
parent 70bfff96e0
commit 4d7fcbe23a

View file

@ -35,17 +35,19 @@ type Hub struct {
// Unregister requests from clients.
unregister chan *Client
mux sync.Mutex
mux sync.Mutex
once sync.Once
}
func (h *Hub) run() {
defer func() {
close(h.closed)
}()
for {
select {
case <-h.quit:
close(h.closed)
return
case <-h.ctx.Done():
close(h.closed)
return
case client := <-h.register:
if client != nil {
@ -116,8 +118,15 @@ func (h *Hub) Start() error {
return nil
}
func (h *Hub) Close() error {
h.once.Do(func() {
close(h.quit)
})
return nil
}
func (h *Hub) Stop() error {
close(h.quit)
h.Close()
select {
case <-h.closed:
return nil