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

16 Go Concurrency Patterns: Timing out, moving on GO并发模式: 超时, 继续前进的更多相关文章

  1. Go Concurrency Patterns: Timing out, moving on

    https://blog.golang.org/go-concurrency-patterns-timing-out-and

  2. Go Concurrency Patterns: Pipelines and cancellation

    https://blog.golang.org/pipelines Go Concurrency Patterns: Pipelines and cancellation Sameer Ajmani1 ...

  3. 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. ...

  4. golang语言中的context详解,Go Concurrency Patterns: Context

    https://blog.golang.org/context Introduction In Go servers, each incoming request is handled in its ...

  5. Advanced Go Concurrency Patterns

    https://talks.golang.org/2013/advconc.slide#5 It's easy to go, but how to stop? Long-lived programs ...

  6. 设计模式教程(Design Patterns Tutorial)笔记之三 行为型模式(Behavioral Patterns)

    目录 · Strategy · When to use the Strategy Design Pattern? · Sample Code · Observer · When to use the  ...

  7. [Python设计模式] 第16章 上班,干活,下班,加班——状态模式

    github地址:https://github.com/cheesezh/python_design_patterns 题目 用代码模拟一天的工作状态,上午状态好,中午想睡觉,下午渐恢复,加班苦煎熬. ...

  8. 设计模式教程(Design Patterns Tutorial)笔记之一 创建型模式(Creational Patterns)

    目录 · 概述 · Factory · What is the Factory Design Pattern? · Sample Code · Abstract Factory · What is t ...

  9. Ubuntu 16.04/CentOS 6.9安装Apache压力(并发)测试工具ab

    说明: ab工具已经在Apache中包含,如果不想安装Apache,那么可以使用下面方法单独安装. 安装: Ubuntu: sudo apt-get install apache2-utils Cen ...

随机推荐

  1. 一文看尽HashMap

    前言 日常开发中,经常会使用到JDK自带的集合类:List.Set.Map三者的实现,ArrayList.LinkedList.HashSet.TreeSet.HashMap.TreeMap等.其中L ...

  2. 【BZOJ4025】二分图(线段树分治,并查集)

    [BZOJ4025]二分图(线段树分治,并查集) 题面 BZOJ 题解 是一个二分图,等价于不存在奇环. 那么直接线段树分治,用并查集维护到达根节点的距离,只计算就好了. #include<io ...

  3. 洛谷 P2389 电脑班的裁员 解题报告

    题意: 给定一段长为N的序列,选取其中的至多M段使这些子段和最大. 当N=1000时,我们可以采用动态规划解法 令\(dp[i][j][k]\)代表当前选至位置\(i\)处于第\(j\)段当前是否选取 ...

  4. 洛谷大宁的邀请赛~元旦祭F: U17264 photo(线段树)

    标程的写法稍微有点麻烦,其实不需要平衡树也是可以做的. 线段树上维护从左端点开始最远的有拍照的长度,以及区间的最大值. 考虑两段区间合并的时候,显然左区间必须取,右区间的第一个比左区间最大值大的数开始 ...

  5. 解题:NOI 2009 管道取珠

    题面 考虑这个平方的实际意义,实际是说取两次取出一样的序列 那么设$dp[i][j][k][h]$表示第一次在上面取$i$个下面取$j$个,第二次在上面取$k$个下面取$h$个的方案数 等等$n^4$ ...

  6. linux命令总结之state命令

    ls 命令及其许多参数提供了一些非常有用的文件信息.另一个不太为人所熟知的命令 stat 提供了一些更为有用的信息. [root@Gin scripts]# man stat STAT() User ...

  7. python 多线程中的同步锁 Lock Rlock Semaphore Event Conditio

    摘要:在使用多线程的应用下,如何保证线程安全,以及线程之间的同步,或者访问共享变量等问题是十分棘手的问题,也是使用多线程下面临的问题,如果处理不好,会带来较严重的后果,使用python多线程中提供Lo ...

  8. Shell记录-Shell命令(find)

    Linux中的find命令在目录结构中搜索文件,并执行指定的操作.Linux下find命令提供了相当多的查找条件,功能很强大.由于find具有强大的功能,所以它的选项也很多,其中大部分选项都值得我们花 ...

  9. 三个你不知道的CSS技巧

    各种浏览器之间的竞争的白热化意味着越来越多的人现在开始使用那些支持最新.最先进的W3C Web标准的设备,以一种更具交互性的方式来访问互联网.这意味着我们终于能够利用更强大更灵活的CSS来创造更简洁, ...

  10. .net WebService 大数据量时性能的提高

    1.直接返回DataSet对象 [WebMethod(Description = "直接返回DataSet对象")] public DataSet GetUserListDateS ...