github.com/graybobo/golang.org-package-offline-cache@v0.0.0-20200626051047-6608995c132f/x/talks/2012/goforc/worker1.go (about) 1 // +build OMIT 2 3 package main 4 5 import "fmt" 6 import "time" 7 8 // START1 OMIT 9 func main() { 10 start := time.Now() 11 12 in := make(chan int) // Channel on which work orders are received. 13 out := make(chan []int) // Channel on which results are returned. 14 go producer(in) 15 go worker(in, out) // Launch one worker. // HL 16 consumer(out, 100) 17 18 fmt.Println(time.Since(start)) 19 } 20 21 // STOP1 OMIT 22 23 // START2 OMIT 24 func worker(in chan int, out chan []int) { 25 for { 26 order := <-in // Receive a work order. // HL 27 result := factor(order) // Do some work. // HL 28 out <- result // Send the result back. // HL 29 } 30 } 31 32 // STOP2 OMIT 33 34 // START3 OMIT 35 func producer(out chan int) { 36 for order := 0; ; order++ { 37 out <- order // Produce a work order. // HL 38 } 39 } 40 41 func consumer(in chan []int, n int) { 42 for i := 0; i < n; i++ { 43 result := <-in // Consume a result. // HL 44 fmt.Println("Consumed", result) 45 } 46 } 47 48 // STOP3 OMIT 49 50 // factor returns a list containing x and its prime factors. 51 func factor(x int) (list []int) { 52 list = append(list, x) 53 for f := 2; x >= f; f++ { 54 for x%f == 0 { 55 x /= f 56 list = append(list, f) 57 // Slow down so we can see what happens. 58 time.Sleep(50 * time.Millisecond) 59 } 60 } 61 return 62 }