diff --git a/go/05-concurrency/select.go b/go/05-concurrency/select.go index 8af6e52..c6c70ed 100644 --- a/go/05-concurrency/select.go +++ b/go/05-concurrency/select.go @@ -1,6 +1,7 @@ package main import ( + "fmt" "math/rand" "time" ) @@ -8,12 +9,46 @@ import ( func main() { ch1 := make(chan string) + ch2 := make(chan string) go func() { time.Sleep(time.Duration(rand.Intn(5)+1) * time.Second) ch1 <- "Message from channel 1" }() - msg1 := <-ch1 - println("Received:", msg1) + go func() { + time.Sleep(time.Duration(rand.Intn(5)+1) * time.Second) + ch2 <- "Message from channel 2" + }() + + count := 10 + var channels []chan string + for i := range count { + ch := make(chan string) + channels = append(channels, ch) + go func() { + time.Sleep(time.Duration(rand.Intn(5)+1) * time.Second) + ch <- fmt.Sprintf("Message from dynamic channel %d", i) + }() + } + + fanIn := make(chan string) + for _, ch := range channels { + go func(c chan string) { + fanIn <- <-c + }(ch) + } + + select { + case msg1 := <-ch1: + println("Received:", msg1) + case msg2 := <-ch2: + println("Received:", msg2) + case msg := <-fanIn: + println("Received:", msg) + case <-time.After(3 * time.Second): + println("Timeout occurred") + default: + println("Nothing") + } }