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. 【BZOJ4247】挂饰(动态规划)

    [BZOJ4247]挂饰(动态规划) 题面 BZOJ 题解 设\(f[i][j]\)表示前\(i\)个物品中还剩下\(j\)个挂钩时的最大答案. 转移显然是一个\(01\)背包,要么不选:\(f[i] ...

  2. 20135319zl软件破解报告

    编写一个简单的C程序.要求只有输入a,才能通过. 现在,使用objdump –d po反汇编这个程序 找到main函数,可以发现movb $0x61,0x1f(%esp)这句语句中是将字符a(对应0x ...

  3. js中相等、大小 不同类型之间是如何进行对比的。

    上个小问题 [] > [] false [] < [] false [] == [] false // why? 再上个加强版 '6xxx' < '5xx' false '6xxx' ...

  4. JFreeChart工具类

    需要的jar包: jfreechart-1.0.17.jarjcommon-1.0.24.jar (jfreechart一般只要1.0系列的都可以,jcommon一般任何版本都可以) 效果: 代码: ...

  5. Chapter 6(树)

    1.树的储存方式 //****************双亲表示法************************ #define Max_TREE_SIZE 100 typedef int TElem ...

  6. ural 2029 Towers of Hanoi Strike Back (数学找规律)

    ural 2029 Towers of Hanoi Strike Back 链接:http://acm.timus.ru/problem.aspx?space=1&num=2029 题意:汉诺 ...

  7. 星号三角形 I

    N = int(eval(input())) for row in range(1,N+1): if row%2 != 0: a = '*'*row print ('{}'.format(a.cent ...

  8. 使用tkinter做简单计算器

    代码如下: from tkinter import * #导入tkinter库 root =Tk() #给窗体 root.title('calculator') #设置窗体名字 frm=Frame(r ...

  9. NATS_01:NATS基础介绍

    1.介绍 NATS(Message bus): 从CloudFoundry的总架构图看,位于各模块中心位置的是一个叫nats的组件.NATS是由CloudFoundry的架构师Derek开发的一个开源 ...

  10. Java消息队列三道面试题详解!

    面试题 为什么使用消息队列? 消息队列有什么优点和缺点? Kafka.ActiveMQ.RabbitMQ.RocketMQ 都有什么区别,以及适合哪些场景? 面试官心理分析 其实面试官主要是想看看: ...