select 多路复用和超时
package _select
import (
"fmt"
"testing"
"time"
)
func service() string {
time.Sleep(time.Millisecond * 500)
return "Done"
}
func AsyncService() chan string{
retch := make(chan string)
go func() {
ret := service()
fmt.Println("return result .")
retch<-ret
fmt.Println("service exited")
}()
return retch
}
func TestService(t *testing.T){
select {
case ret := <-AsyncService():
t.Log(ret)
case <-time.After(time.Millisecond * 100):
t.Error("time out ...")
}
}
该篇博客探讨了Go语言中`select`关键字如何用于多路复用和超时控制。通过一个示例,展示了如何在调用异步服务时设置100毫秒的超时限制。如果服务在规定时间内返回,它将打印返回结果;否则,将触发超时错误。这展示了Go在并发编程中的灵活性和控制力。

被折叠的 条评论
为什么被折叠?



