github.com/graybobo/golang.org-package-offline-cache@v0.0.0-20200626051047-6608995c132f/x/talks/2012/10things/10.go (about) 1 // +build OMIT 2 3 package main 4 5 import ( 6 "fmt" 7 "math/rand" 8 "time" 9 ) 10 11 func worker(i int, ch chan Work, quit chan struct{}) { 12 for { 13 select { 14 case w := <-ch: 15 if quit == nil { // HL 16 w.Refuse(); fmt.Println("worker", i, "refused", w) 17 break 18 } 19 w.Do(); fmt.Println("worker", i, "processed", w) 20 case <-quit: 21 fmt.Println("worker", i, "quitting") 22 quit = nil // HL 23 } 24 } 25 } 26 27 func main() { 28 ch, quit := make(chan Work), make(chan struct{}) 29 go makeWork(ch) 30 for i := 0; i < 4; i++ { go worker(i, ch, quit) } 31 time.Sleep(5 * time.Second) 32 close(quit) 33 time.Sleep(2 * time.Second) 34 } 35 // endmain OMIT 36 37 type Work string 38 func (w Work) Do() { 39 time.Sleep(time.Duration(rand.Intn(1000)) * time.Millisecond) 40 } 41 func (w Work) Refuse() { 42 time.Sleep(time.Duration(rand.Intn(10)) * time.Millisecond) 43 } 44 45 func makeWork(ch chan Work) { 46 for i := 0; ; i++ { 47 ch <- Work(fmt.Sprintf("job %x", i)) 48 } 49 }