1. 程式人生 > >Go Concurrency Patterns: Timing out, moving on

Go Concurrency Patterns: Timing out, moving on

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 select statement 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.

相關推薦

16 Go Concurrency Patterns: Timing out, moving on

allocated mea AMM condition package rev fun min example Go Concurrency Patterns: Timing out, moving on 23 September 2010 Concurrent prog

Go Concurrency Patterns: Timing out, moving on

23 September 2010 Concurrent programming has its own idioms. A good example is timeouts. Although Go's chann

NYC: Where to go for a night out based on noise complaints

Fast Facts1) Pick your borough wisely…The height of the bars represents the average number of noise complaints by bar by year for each borough. The width i

Go Concurrency Patterns: Pipelines and cancellation

13 March 2014 Introduction Go's concurrency primitives make it easy to construct streaming data pipelines

Go Concurrency Patterns: Context

29 July 2014 Introduction In Go servers, each incoming request is handled in its own goroutine. Request ha

Why does Delphi XE7 IDE hangs and fails on out of memory exception?

problem cycle soft addition des microsoft same hour bsp 引自: https://stackoverflow.com/questions/27701294/why-does-delphi-xe7-ide-ha

ystem.TimeoutException: The operation requested on PersistentChannel timed out.

Error:System.TimeoutException: The operation requested on PersistentChannel timed out.    在 EasyNetQ.Producer.ClientCommandDispatcherSingle

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.22.1:test (default-test) on project sharp-common: Execution default-test of go

1 [INFO] Scanning for projects... 2 [INFO] 3 [INFO] -----------------------< com.sharp:sharp-common >----------------------- 4 [INFO] Buildin

jQuery事件--change([[data],fn])、on(events,[selector],[data],fn)和hover([over,]out)

   change([[data],fn]) 概述     當元素的值發生改變時,會發生 change 事件。     該事件僅適用於文字域(text field),以及 textarea 和 select 元素。當用於 sel

perationalError: (2003, "Can't connect to MySQL server on u'192.168.1.6' (timed out)")

在Ubuntu(192.168.1.20)中部署專案後,mysql還在另外一臺windows(192.168.1.6)機子上,ping windows時可以ping通,但是訪問專案提示: perationalError: (2003, "Can't connect to MySQL server on u'

on with Microsoft's Surface Headphones: tune out the outside world to focus | AITopics

If the theme of Microsoft's Tuesday Surface event was about maintaining focus, then the new Microsoft Surface Headphones fall right in line: Spin the noise

Google Assistant makes it easier to go clothes shopping on Asos

Looking at clothes to buy online can be therapeutic, but sometimes you just want to quickly find something to wear for an impromptu event without having to

Ask HN: Is it a pain paying out revenue share on collaborative projects?

I've worked on several collaborative projects in which I agree to split the revenues with someone. Books is the big use case. Amazon doesn't split paymen

You’re Missing Out on a Better Mac Terminal Experience

Mac command line apps, plugins, tweaks, and tips to make your terminal exactly what you want it to be: functional, minimal, aesthetic, or all of the above-

Go Serverless! Let’s create a File Sharing application based on AWS services

Let’s start illustrating the services that are utilized according to design choices.Amazon S3“Amazon S3 is an object storage service created to memorize an

Licenses Of Content Used On This Website · Applied Go

Applied Go by Christoph Berger is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. Th

In the news: Go on AWS Lambda · Applied Go

On Jan 15th, Amazon announced Go support for AWS Lambda. This was exciting news for many, according to the number of blog posts that followed this annou

Setup and config Go environment on Ubuntu 16.04 and Centos 7

Recently somebody have some questions for me. Why i can’t run go get ? How to change workspace project with Go ? Why after i exit session on terminal

Video series: Running Go programs on Raspberry Pi @ Alex Pliutau's Blog

I started new video series about writing and running Go programs on Raspberry Pi. In these videos I will cover: Capture image on Raspberry P

動畫效果&Fade in Fade out ft. Go Away Big Green Monster

動畫效果&Fade in Fade out ft. Go Away Big Green Monster很多的繪本本身在翻閱的時候,就有動畫的概念與效果了,例如《Go Away, Big Green Monster 》這本就是。從解構怪獸的過程, 可以讓小朋友知道,再可怕的東西,都只是堆疊而來的心裡恐懼,跟大人