dongshu7162 2019-08-07 15:56
浏览 22
已采纳

等待两个结果同时超时

Use case

I'd like to run two queries against a database in parallel and return after a maximum time of 600ms whatever I have fetched to that point. I am struggling with implementing the concurrency for this requirement.

Code

func (s *Service) GetCustomerStats(ctx context.Context, customerUUID string) *CustomerStats {
    stats := &CustomerStats{
        CustomerUUID: customerUUID,
        Type:         "ERROR",
        OrderCount:   "ERROR",
    }

    var wg sync.WaitGroup
    var mu sync.Mutex

    // Get order count
    wg.Add(1)
    go func() {
        defer wg.Done()
        orderCount, err := s.Storage.GetOrderCount(ctx, customerUUID)
        if err != nil {
            return
        }

        mu.Lock()
        stats.OrderCount = strconv.Itoa(orderCount)
        if orderCount == 0 {
            stats.OrderCount = "NA"
        }
        mu.Unlock()
    }()

    // Get customer type
    wg.Add(1)
    go func() {
        defer wg.Done()
        type, err := s.Storage.GetCustomerType(ctx, customerUUID)
        if err != nil {
            return
        }

        mu.Lock()
        stats.Type = strconv.Itoa(type)
        mu.Unlock()
    }()

    wg.Wait()

    return stats
}

The problem

The context I pass into that function has a timeout of 600ms defined. I pass it on to the storage repo and the Database driver uses it as well, but it does not guarantee it will respond within that time as it does schedule some retries under the hood.

However I must ensure that this function returns within the passed context timeout (600ms). I am currently using a waitgroup to await the results but I wouldn't know how to return stats once the context is done.

Basically I am looking for something like this. My research indicates that I should probably use channels which signal that the work is done but I am not sure how I would implement that so that it's simple code.

    select {
    case wg.Wait()
        return stats
    case <-ctx.Done()
        return stats
    }
  • 写回答

1条回答 默认 最新

  • dongye7231 2019-08-07 16:10
    关注

    The way you plan to select on ctx.Done() looks correct.
    It's the way you work with your mutable state that is wrong, in my opinion.

    Try something like this:

     var state = State{}
     select {
        case type <- typeChan
            stats.Type = type
            if (stats.OrderCount != nil) {
               return stats
            }
        case count <- countChan
            stats.OrderCount = count
            if (stats.Type != nil) {
               return stats
            }
        case <-ctx.Done()
            return stats
        }
    

    Now your functions should look like this:

    go func() {        
        orderCount, err := s.Storage.GetOrderCount(ctx, customerUUID)
        if err != nil {
            return // Here you probably want to have errChan
        }
    
        if orderCount == 0 {
            countChan <- "NA"
        } else {
            countChan <- strconv.Itoa(orderCount)
        }        
    }()
    

    This is all a bit sketchy, since your example is quite complex, but should give you the direction to follow.

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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度