16 Go Concurrency Patterns: Timing out, moving on GO并发模式: 超时, 继续前进
Go Concurrency Patterns: Timing out, moving on GO并发模式: 超时, 继续前进
23 September 2010
Concurrent programming has its own idioms. A good example is timeouts. Although Go's channels do not support them directly, they are easy to implement. Say we want to receive from the channel ch, but want to wait at most one second for the value to arrive. We would start by creating a signalling channel and launching a goroutine that sleeps before sending on the channel:
timeout := make(chan bool, 1)
go func() {
time.Sleep(1 * time.Second)
timeout <- true
}()
We can then use a select statement to receive from either ch or timeout. If nothing arrives on ch after one second, the timeout case is selected and the attempt to read from ch is abandoned.
select {
case <-ch:
// a read from ch has occurred
case <-timeout:
// the read from ch has timed out
}
The timeout channel is buffered with space for 1 value, allowing the timeout goroutine to send to the channel and then exit. The goroutine doesn't know (or care) whether the value is received. This means the goroutine won't hang around forever if the ch receive happens before the timeout is reached. The timeout channel will eventually be deallocated by the garbage collector.
(In this example we used time.Sleep to demonstrate the mechanics of goroutines and channels. In real programs you should use ` time.After`, a function that returns a channel and sends on that channel after the specified duration.)
Let's look at another variation of this pattern. In this example we have a program that reads from multiple replicated databases simultaneously. The program needs only one of the answers, and it should accept the answer that arrives first.
The function Query takes a slice of database connections and a query string. It queries each of the databases in parallel and returns the first response it receives:
func Query(conns []Conn, query string) Result {
ch := make(chan Result)
for _, conn := range conns {
go func(c Conn) {
select {
case ch <- c.DoQuery(query):
default:
}
}(conn)
}
return <-ch
}
In this example, the closure does a non-blocking send, which it achieves by using the send operation in selectstatement with a default case. If the send cannot go through immediately the default case will be selected. Making the send non-blocking guarantees that none of the goroutines launched in the loop will hang around. However, if the result arrives before the main function has made it to the receive, the send could fail since no one is ready.
This problem is a textbook example of what is known as a race condition, but the fix is trivial. We just make sure to buffer the channel ch (by adding the buffer length as the second argument to make), guaranteeing that the first send has a place to put the value. This ensures the send will always succeed, and the first value to arrive will be retrieved regardless of the order of execution.
These two examples demonstrate the simplicity with which Go can express complex interactions between goroutines.
By Andrew Gerrand
Related articles
- HTTP/2 Server Push
- Introducing HTTP Tracing
- Generating code
- Go Concurrency Patterns: Context
- Go Concurrency Patterns: Pipelines and cancellation
- Introducing the Go Race Detector
- Advanced Go Concurrency Patterns
- Go maps in action
- go fmt your code
- Concurrency is not parallelism
- Organizing Go code
- Go videos from Google I/O 2012
- Debugging Go programs with the GNU Debugger
- The Go image/draw package
- The Go image package
- The Laws of Reflection
- Error handling and Go
- "First Class Functions in Go"
- Profiling Go Programs
- A GIF decoder: an exercise in Go interfaces
- Introducing Gofix
- Godoc: documenting Go code
- Gobs of data
- C? Go? Cgo!
- JSON and Go
- Go Slices: usage and internals
- Defer, Panic, and Recover
- Share Memory By Communicating
- JSON-RPC: a tale of interfaces
16 Go Concurrency Patterns: Timing out, moving on GO并发模式: 超时, 继续前进的更多相关文章
- Go Concurrency Patterns: Timing out, moving on
https://blog.golang.org/go-concurrency-patterns-timing-out-and
- Go Concurrency Patterns: Pipelines and cancellation
https://blog.golang.org/pipelines Go Concurrency Patterns: Pipelines and cancellation Sameer Ajmani1 ...
- Go Concurrency Patterns: Context At Google, we require that Go programmers pass a Context parameter as the first argument to every function on the call path between incoming and outgoing requests.
小结: 1. Background is the root of any Context tree; it is never canceled: 2. https://blog.golang. ...
- golang语言中的context详解,Go Concurrency Patterns: Context
https://blog.golang.org/context Introduction In Go servers, each incoming request is handled in its ...
- Advanced Go Concurrency Patterns
https://talks.golang.org/2013/advconc.slide#5 It's easy to go, but how to stop? Long-lived programs ...
- 设计模式教程(Design Patterns Tutorial)笔记之三 行为型模式(Behavioral Patterns)
目录 · Strategy · When to use the Strategy Design Pattern? · Sample Code · Observer · When to use the ...
- [Python设计模式] 第16章 上班,干活,下班,加班——状态模式
github地址:https://github.com/cheesezh/python_design_patterns 题目 用代码模拟一天的工作状态,上午状态好,中午想睡觉,下午渐恢复,加班苦煎熬. ...
- 设计模式教程(Design Patterns Tutorial)笔记之一 创建型模式(Creational Patterns)
目录 · 概述 · Factory · What is the Factory Design Pattern? · Sample Code · Abstract Factory · What is t ...
- Ubuntu 16.04/CentOS 6.9安装Apache压力(并发)测试工具ab
说明: ab工具已经在Apache中包含,如果不想安装Apache,那么可以使用下面方法单独安装. 安装: Ubuntu: sudo apt-get install apache2-utils Cen ...
随机推荐
- javascript和php使用ajax通信传递JSON
JS和PHP直接通信常用ajax完成,以实现js上UI的动态变化.通信使用JSON或者XML传递数据.下面详细描述两者直接JSON字符串的传递. 下面案例是要传递这样的json数据: { " ...
- Springboot返回html
注:Springboot的版本2.1.3.RELEASE List-1 application.properties文件 server.port=8080 #url中,项目的前缀 server.ser ...
- easyui的datebox只显示年月
要求点击easyui的datebox时只显示年月,隐藏日,之前百度了好多,发现有的好麻烦,有的使用没效果,也许自己没理解,改不了.最后老员工帮我搞定了,添加一个fomatter和一个parser函数就 ...
- 51nod 1571 最近等对 | 线段树 离线
51nod 1571 最近等对 题面 现在有一个序列 a1, a2, ..., an ,还有m个查询 lj, rj (1 ≤ lj ≤ rj ≤ n) .对于每一个查询,请找出距离最近的两个元素 ax ...
- Monitor WMIExportsToC++Use DiskCleanup bypass UAC
作者:嘶吼吼链接:https://zhuanlan.zhihu.com/p/23473665来源:知乎著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注明出处. About: Use odb ...
- Android Studio中多项目共享Library
FAQ: as的projectA中有一个commonLib的源码库模块,projectB要调用其中的commonLib, 这个有没有方案?不用手动拷贝aar的 方案1. 采用gradle配置参数方 ...
- Android源码批量下载及导入到Eclipse
1.去http://code.google.com/p/msysgit/downloads/list 下载Git,进行安装 2.生成批量下载脚本文件 下载批量工具CreatAutoGetSh(工具 ...
- sql 事务的四种隔离级别
在 SQL 标准中定义了四种隔离级别,每一种级别都规定了一个事务中所做的修改,哪些在事务内和事务间是可见的,哪些是不可见的.较低级别的隔离通常可以执行更高的并发,系统的开销也更低. read unco ...
- python抓取
我要抓取奥巴马每周的演讲内容http://www.putclub.com/html/radio/VOA/presidentspeech/index.html 如果手动提取,就需要一个个点进去,再复制保 ...
- windows10 conda2 使用caffe训练训练自己的数据
首先得到了https://blog.csdn.net/gybheroin/article/details/72581318系列博客的帮助.表示感激. 关于安装caffe已在之前的博客介绍,自用可行,h ...