Skip to content

Instantly share code, notes, and snippets.

@r9y9
Created December 27, 2013 02:19
Show Gist options
  • Save r9y9/8141614 to your computer and use it in GitHub Desktop.
Save r9y9/8141614 to your computer and use it in GitHub Desktop.
An example of concurrency best practices from http://talks.golang.org/2013/bestpractices.slide#28
package main
import (
"fmt"
"time"
)
type Server struct {
quit chan bool
}
func NewServer() *Server {
s := &Server{make(chan bool)}
go s.run()
return s
}
func (s *Server) run() {
for {
select {
case <-s.quit:
fmt.Println("finishing task")
time.Sleep(time.Second)
fmt.Println("task done")
s.quit <- true
return
case <-time.After(time.Second):
fmt.Println("running task")
}
}
}
func (s *Server) Stop() {
fmt.Println("server stopping")
s.quit <- true
<-s.quit
fmt.Println("server stopped")
}
func main() {
s := NewServer()
time.Sleep(2*time.Second)
s.Stop()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment