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 ...
随机推荐
- 单点登录(十五)-----实战-----cas4.2.x登录mongodb验证方式实现自定义加密
我们在前一篇文章中实现了cas4.2.x登录使用mongodb验证方式. 单点登录(十三)-----实战-----cas4.2.X登录启用mongodb验证方式完整流程 也学习参考了cas5.0.x版 ...
- 【线性基/神仙题】P4151 [WC2011]最大XOR和路径
Description 给定一个无向连通图,边有边权,求一个 \(1~\sim n\) 的路径,最大化边权的异或和.如果一条边经过多次则计算多次. Input 第一行是两个整数 \(n,m\) 代表点 ...
- Linux crontab 命令格式与举例
每五分钟执行 */5 * * * * 每小时执行 0 * * * * 每天执行 0 0 * * * 每周执行 0 0 * * 0 每月执行 0 0 1 ...
- 树状数组+二分答案查询第k大的数 (团体程序设计天梯赛 L3-002. 堆栈)
前提是数的范围较小 1 数据范围:O(n) 2 查第k大的数i:log(n)(树状数组查询小于等于i的数目)*log(n)(二分找到i) 3 添加:log(n) (树状数组) 4 删除:log(n) ...
- [opencv] 图像几何变换:旋转,缩放,斜切
几何变换 几何变换可以看成图像中物体(或像素)空间位置改变,或者说是像素的移动. 几何运算需要空间变换和灰度级差值两个步骤的算法,像素通过变换映射到新的坐标位置,新的位置可能是在几个像素之间,即不一定 ...
- HDU 3271 数位dp+二分
SNIBB Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submi ...
- mysql 设置默认编码为 utf8
vi /etc/mysql/mysql.conf.d/mysqld.cnf [client] default-character-set=utf8 [mysql] default-character- ...
- Hadoop生态圈-Hive快速入门篇之HQL的基础语法
Hadoop生态圈-Hive快速入门篇之HQL的基础语法 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 本篇博客的重点是介绍Hive中常见的数据类型,DDL数据定义,DML数据操作 ...
- day3 程序流程控制
今天主要学习了while和do/while,以及运用循环做一些小的练习. 学习了如何断点调试程序. 程序设计的步骤: 1.分析问题 2.确定数据结构和算法 3.编制程序 4.调试问题
- windows下静态编译pthread
1. Building the library as a statically linkable library-------------------------------------------- ...