- Go语言入门
- Go语言开发环境安装配置
- Go语言程序结构
- Go语言基础语法
- Go语言数据类型
- Go语言变量
- Go语言常量
- Go语言运算符
- Go语言条件和决策
- Go语言循环
- Go语言函数
- Go语言作用域规则
- Go语言字符串
- Go语言数组
- Go语言指针
- Go语言结构体
- Go语言切片
- Go语言范围(range)
- Go语言映射
- Go语言递归
- Go语言类型转换
- Go语言接口
- Go语言错误处理
-
Go编程代码实例
- Hello World程序实例
- Go变量实例
- Go常量实例
- Go for循环语句实例
- Go if/else语句实例
- Go switch语句实例
- Go切片实例
- Go范围实例
- Go函数实例
- Go函数多个返回值实例
- Go可变参数的函数实例
- Go闭包(匿名函数)实例
- Go函数递归实例
- Go指针实例
- Go指针实例
- Go接口实例
- Go错误实例
- Go程序实例
- Go通道实例
- Go通道缓冲实例
- Go通道同步实例
- Go通道路线实例
- Go Select实例
- Go超时(timeouts)实例
- Go非阻塞通道操作实例
- Go关闭通道实例
- Go通道范围实例
- Go计时器实例
- Go断续器实例
- Go工作池实例
- Go速率限制实例
- Go原子计数器实例
- Go互斥体实例
- Go有状态的goroutines实例
- Go排序实例
- Go按自定义函数排序实例
- Go panic错误处理实例
- Go延迟(defer)实例
- Go集合函数实例
- Go字符串函数实例
- Go字符串格式化实例
- Go正则表达式实例
- Go JSON实例
- Go时间日期实例
- Go时代(Epoch)实例
- Go时间格式化/解析实例
- Go随机数实例
- Go数字解析实例
- Go URL解析实例
- Go SHA1哈希实例
- Go Base64编码实例
- Go读取文件实例
- Go写文件实例
- Go行过滤器实例
- Go命令行参数实例
- Go命令行标志实例
- Go环境变量实例
- Go执行过程实例
- Go信号实例
- Go退出程序实例
Go超时(timeouts)实例
超时对于连接到外部资源或在不需要绑定执行时间的程序很重要。在Go编程中由于使用了通道和选择(select),实现超时是容易和优雅的。
在这个示例中,假设正在执行一个外部调用,2
秒后在通道c1
上返回其结果。
这里是 select
实现超时。 res:= <-c1
等待结果和<-Time
。等待在超时1
秒后发送一个值。 由于选择继续准备好第一个接收,如果操作超过允许的1
秒,则将按超时情况处理。
如果允许更长的超时,如:3s
,那么从c2
的接收将成功,这里将会打印结果。
运行此程序显示第一个操作超时和第二个操作超时。
使用此选择超时模式需要通过通道传达结果。这是一个好主意,因为其他重要的Go
功能是基于渠道和Select
。现在看看下面的两个例子:计时器和ticker
。
所有的示例代码,都放在
F:\worksp\golang
目录下。安装Go编程环境请参考:/tutorial/detail-5562.html
timeouts.go
的完整代码如下所示 -
package main import "time" import "fmt" func main() { // For our example, suppose we're executing an external // call that returns its result on a channel `c1` // after 2s. c1 := make(chan string, 1) go func() { time.Sleep(time.Second * 2) c1 <- "result 1" }() // Here's the `select` implementing a timeout. // `res := <-c1` awaits the result and `<-Time.After` // awaits a value to be sent after the timeout of // 1s. Since `select` proceeds with the first // receive that's ready, we'll take the timeout case // if the operation takes more than the allowed 1s. select { case res := <-c1: fmt.Println(res) case <-time.After(time.Second * 1): fmt.Println("timeout 1") } // If we allow a longer timeout of 3s, then the receive // from `c2` will succeed and we'll print the result. c2 := make(chan string, 1) go func() { time.Sleep(time.Second * 2) c2 <- "result 2" }() select { case res := <-c2: fmt.Println(res) case <-time.After(time.Second * 3): fmt.Println("timeout 2") } }
执行上面代码,将得到以下输出结果 -
F:\worksp\golang>go run timeouts.go timeout 1 result 2
上一篇:Go Select实例
下一篇:Go非阻塞通道操作实例