You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Go runtime holds waiting FIFO queue for receivers (goroutines ready to receive on the particular channel)
多个goroutine产生 channel value 最终汇聚到某个 channel (fan-in)
某个channel的值分发到多个goroutine (worker pattern)
Patterns
Generator:funciton that returns a channel
func boring(msg string) <-chan string { // Returns receive-only channel of strings.
c := make(chan string)
go func() { // We launch the goroutine from inside the function.
for i := 0; ; i++ {
c <- fmt.Sprintf("%s %d", msg, i)
time.Sleep(time.Duration(rand.Intn(1e3)) * time.Millisecond)
}
}()
return c // Return the channel to the caller.
}
Timeout using select
func main() {
c := boring("Joe")
for {
select {
case s := <-c:
fmt.Println(s)
case <-time.After(1 * time.Second):
fmt.Println("You're too slow.")
return
}
}
}
Timeout for whole conversation using select
Create the timer once, outside the loop, to time out the entire conversation.
func main() {
c := boring("Joe")
timeout := time.After(5 * time.Second)
for {
select {
case s := <-c:
fmt.Println(s)
case <-timeout:
fmt.Println("You talk too much.")
return
}
}
}
Daisy-chain
func f(left, right chan int) {
left <- 1 + <-right
}
func main() {
const n = 10000
leftmost := make(chan int)
right := leftmost
left := leftmost
for i := 0; i < n; i++ {
right = make(chan int)
go f(left, right)
left = right
}
go func(c chan int) { c <- 1 }(right)
fmt.Println(<-leftmost)
}
Google Search ,Example
同步阻塞方式
fan-in 方式
fan-in + timeout
avoid discarding results from slow servers.Send requests to multiple replicas, and use the first response(对提供相同服务的多个服务器发送请求,取最快的那个)
Links
The text was updated successfully, but these errors were encountered:
Google I/O 2012 - Go Concurrency Patterns
Rob Pike:
Go runtime holds waiting FIFO queue for receivers (goroutines ready to receive on the particular channel)
多个goroutine产生 channel value 最终汇聚到某个 channel (fan-in)
某个channel的值分发到多个goroutine (worker pattern)
Patterns
Timeout for whole conversation using select
Create the timer once, outside the loop, to time out the entire conversation.
Google Search ,Example
Links
The text was updated successfully, but these errors were encountered: