Created
December 27, 2013 02:19
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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