1
0
Fork 0
main^2
Sebastian Steger 2025-08-20 11:36:48 +00:00
parent c47b686210
commit 78d18901c1
1 changed files with 37 additions and 2 deletions

View File

@ -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")
}
}