github.com/graybobo/golang.org-package-offline-cache@v0.0.0-20200626051047-6608995c132f/x/talks/2012/goforc/worker2.go (about)

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