Last active
February 24, 2021 14:08
-
-
Save noyv/63be793ba6d884cde371fd49781fdacd to your computer and use it in GitHub Desktop.
thought for www.v2ex.com/t/755876
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"log" | |
"math/rand" | |
"sync" | |
"time" | |
) | |
func main() { | |
c := make(chan int) | |
rc := make(chan int) | |
go func() { | |
for i := 0; i < 10; i++ { | |
time.Sleep(time.Duration(rand.Intn(10))*time.Millisecond) | |
c <- i | |
} | |
}() | |
wg := sync.WaitGroup{} | |
wg.Add(5) | |
for i := 0; i < 4; i++ { | |
go func() { | |
out: | |
for { | |
select { | |
case t := <-c: | |
time.Sleep(time.Duration(rand.Intn(1000))*time.Millisecond) | |
rc <- (t + 10) | |
case <-time.After(time.Second): | |
break out | |
} | |
} | |
wg.Done() | |
}() | |
} | |
go func() { | |
out: | |
for { | |
select { | |
case t := <-rc: | |
time.Sleep(time.Duration(rand.Intn(100))*time.Millisecond) | |
log.Println(t) | |
case <-time.After(time.Second): | |
break out | |
} | |
} | |
wg.Done() | |
}() | |
wg.Wait() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment