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