github.com/graybobo/golang.org-package-offline-cache@v0.0.0-20200626051047-6608995c132f/x/talks/2012/concurrency/support/sequenceboring.go (about) 1 // +build OMIT 2 3 package main 4 5 import ( 6 "fmt" 7 "math/rand" 8 "time" 9 ) 10 11 // START0 OMIT 12 type Message struct { 13 str string 14 wait chan bool // HL 15 } 16 // STOP0 OMIT 17 18 func main() { 19 c := fanIn(boring("Joe"), boring("Ann")) // HL 20 // START1 OMIT 21 for i := 0; i < 5; i++ { 22 msg1 := <-c; fmt.Println(msg1.str) 23 msg2 := <-c; fmt.Println(msg2.str) 24 msg1.wait <- true 25 msg2.wait <- true 26 } 27 // STOP1 OMIT 28 fmt.Println("You're all boring; I'm leaving.") 29 } 30 31 func boring(msg string) <-chan Message { // Returns receive-only channel of strings. // HL 32 c := make(chan Message) 33 // START2 OMIT 34 waitForIt := make(chan bool) // Shared between all messages. 35 // STOP2 OMIT 36 go func() { // We launch the goroutine from inside the function. // HL 37 for i := 0; ; i++ { 38 // START3 OMIT 39 c <- Message{ fmt.Sprintf("%s: %d", msg, i), waitForIt } 40 time.Sleep(time.Duration(rand.Intn(2e3)) * time.Millisecond) 41 <-waitForIt 42 // STOP3 OMIT 43 } 44 }() 45 return c // Return the channel to the caller. // HL 46 } 47 48 49 // START3 OMIT 50 func fanIn(inputs ... <-chan Message) <-chan Message { // HL 51 c := make(chan Message) 52 for i := range inputs { 53 input := inputs[i] // New instance of 'input' for each loop. 54 go func() { for { c <- <-input } }() 55 } 56 return c 57 } 58 // STOP3 OMIT