Golang concurrency mode: timeout and Continue go Concurrency patterns:timing out, moving on

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Translated from Go Blog.
Original address: Https://blog.golang.org/go-concurrency-patterns-timing-out-and

Concurrent programming has some of its own idioms, and timeouts are one of them. Although the Golang pipeline does not support timeouts directly, it is not difficult to implement. Suppose you encounter a scenario where you wait at least 1 seconds before you take a value from pipe ch. We can create a pipeline to pass a signal, open a process to sleep for a second, and then pass a value to the pipeline.

timeout := make(chan bool, 1)go func() {    time.Sleep(1 * time.Second)    timeout <- true}()

You can then use a SELECT statement to get the data from the timeout or CH pipeline. If the CH pipeline does not return data after 1 seconds, the time-out criterion will trigger the read operation of CH to be discarded.

select {    case <-ch:    // a read from ch has occurred    case <-timeout:    // the read from ch has timed out}

The timeout pipeline has a buffer space of 1, so the timeout process exits execution after the message is sent to the pipeline. The co-process does not know (and does not care) whether the values in the pipeline are accepted. Therefore, even if the CH pipeline is returned before the timeout pipeline, the timeout process does not wait forever. The timeout pipeline will eventually be reclaimed by the garbage collection mechanism.

(In the example above we used time.) The Sleep method demonstrates the mechanics of the process and the pipeline, but should use time in real code. After method, the method returns a pipe and writes a message to the pipeline after the time specified by the parameter

Let's look at another variant of this pattern. We need to fetch data from multiple shard databases at the same time, and the program only needs the data that is returned first.

The following query method accepts two parameters: a database-linked slice and a database query statement. This method queries all the databases in parallel and returns the first accepted response result.

func Query(conns []Conn, query string) Result {    ch := make(chan Result, 1)    for _, conn := range conns {        go func(c Conn) {            select {            case ch <- c.DoQuery(query):            default:            }        }(conn)    }    return <-ch}

In the above example, the closure after the GO keyword implements a non-blocking query request because the Doquery method is placed in a SELECT statement with the default branch. If the Doquery method does not return immediately, the default branch will be selected for execution. Making the query request non-blocking guarantees that the coprocessor created in the For loop will not block all the time. In addition, if a second query result is returned before the main method takes the value out of the CH pipeline and returns the result, the write operation of the pipe CH will fail because the pipeline is not ready.

The problem described above is actually a typical example of a "competitive relationship", and the sample code is a very popular solution. We just set the buffer in the pipeline (by passing in the second parameter in the Make method of the pipeline), which guarantees that the first writer has room to write the value. This strategy ensures that the first write to the pipeline will succeed, regardless of the order in which the code is executed, and the first value written will be treated as the final return value.

The two examples above are the simplest proof of the complex collaboration that can be preceded by the

Go process.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.