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 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line