Skip to content

Instantly share code, notes, and snippets.

@fortytw2
Last active September 15, 2024 19:52
Show Gist options
  • Save fortytw2/f716aff1d11fb90d4696bb7bf582464e to your computer and use it in GitHub Desktop.
Save fortytw2/f716aff1d11fb90d4696bb7bf582464e to your computer and use it in GitHub Desktop.
shutdown
package main
type Server struct {
shutdown chan struct{}
close chan struct{}
}
func NewServer() *Server {
s := &Server{
shutdown: make(chan struct{}, 0),
close: make(chan struct{}, 0),
}
go s.loop()
return s
}
func (s *Server) loop() {
defer func() {
s.close <- struct{}{}
}()
for {
select {
case <-s.shutdown:
// do any cleanup
return
case f <- whatever:
// do some stuf....
f()
}
}
}
func (s *Server) Stop() {
s.shutdown <- struct{}{}
<-s.close
}
@bagardavidyanisntreal
Copy link

mb better close(s.shutdown)?

@buldumac
Copy link

mb better close(s.shutdown)?

for this particular case either way is ok

if it's used in multiple goroutines for stop purpose then yes, we need to use close instead

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment