douhuxi4145 2015-11-04 16:15
浏览 29
已采纳

当第一个完成时如何安全绕开其他goroutine的结果

I want to ask several servers for data (e.g. multiple read replicas). In this task most important is speed, so first result should be served and all other can be ignored.

I have problem with idiomatic way of bypassing this data. Everything with this problem is ok when it quits (all slower goroutines are not finishing their work, because main process exists). But when we uncomment last line (with Sleep) We can see that other goroutines are doing their work too.

Now I'm pushing data through channel is there any way to not push them?

What is good and safe way of dealing with this kind of problems?

package main

import (
    "fmt"
    "log"
    "math/rand"
    "time"
)

type Result int

type Conn struct {
    Id int
}

func (c *Conn) DoQuery(params string) Result {
    log.Println("Querying start", params, c.Id)
    time.Sleep(time.Duration(rand.Int31n(1000)) * time.Millisecond)
    log.Println("Querying end", params, c.Id)

    return Result(1000 + c.Id*c.Id)
}

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

    return <-ch
}

func main() {
    conns := []Conn{Conn{1}, Conn{2}, Conn{3}, Conn{4}, Conn{5}}
    result := Query(conns, "query!")
    fmt.Println(result)
    // time.Sleep(time.Minute)
}
  • 写回答

1条回答 默认 最新

  • duanmeng3573 2015-11-04 16:35
    关注

    My recommendation would be to make ch a buffered channel with one space per query: ch := make(chan Result, len(conns)). This way each query can run to completion, and will not block on the channel write.

    Query can read once and return the first result. When all other goroutines complete, the channel will eventually be garbage collected and everything will go away. With your unbuffered channel, you create a lot of goroutines that can never terminate.

    EDIT: If you want to cancel in-flight requests, it can become significantly harder. Some operations and apis provide cancellation, and others don't. With an http request you can use Cancel field on the request struct. Simply provide a channel that you can close to cancel:

    func (c *Conn) DoQuery(params string, cancel chan struct{}) Result {
        //error handling omitted. It is important to handle errors properly. 
        req, _ := http.NewRequest(...)
        req.Cancel = cancel
        resp, _ := http.DefaultClient.Do(req)
        //On Cancellation, the request will return an error of some kind.
        return readData(resp)
    }
    func Query(conns []Conn, query string) Result {
        ch := make(chan Result)
        cancel := make(chan struct{})
        for _, conn := range conns {
            go func(c Conn) {
                ch <- c.DoQuery(query,cancel)
            }(conn)
        }
    
        first := <-ch
        close(cancel)
        return first
    }
    

    This may help if there is a large request to read that you won't care about, but it may or may not actually cancel the request on the remote server. If your query is not http, but a database call or something else, you will need to look into if there is a similar cancellation mechanism you can use.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 informer代码训练自己的数据集,改参数怎么改
  • ¥15 请看一下,学校实验要求,我需要具体代码
  • ¥50 pc微信3.6.0.18不能登陆 有偿解决问题
  • ¥20 MATLAB绘制两隐函数曲面的交线
  • ¥15 求TYPCE母转母转接头24PIN线路板图
  • ¥100 国外网络搭建,有偿交流
  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验