dongming4994 2018-09-18 22:06
浏览 16

进行例行泄漏修复

I am working on a small service at the moment. From my testing, the code I've written has the possibility of leaking go routines under certain circumstances pertaining to the context. Is there a good and/or idiomatic way to remedy this? I'm providing some sample code below.

func Handle(ctx context.Context, r *Req) (*Response, error) {
    ctx, cancel := context.WithTimeout(ctx, time.Second * 5)
    defer cancel()

    resChan := make(chan Response)
    errChan := make(chan error)

    go process(r, resChan, errChan)

    select {
    case ctx.Done():
        return nil, ctx.Err()
    case res := <-resChan:
        return &res, nil
    case err := <-errChan:
        return nil, err
    }
}

func process(r *Req, resChan chan<- Response, errChan chan<- error) {
    defer close(errChan)
    defer close(resChan)

    err := doSomeWork()
    if err != nil {
        errChan <- err
        return
    }

    err = doSomeMoreWork()
    if err != nil {
        errChan <- err
        return
    }

    res := Response{}
    resChan <- res
}

Hypothetically, if the client cancelled the context or the timeout occurred before the process func had a chance to send on one of the unbuffered channels (resChan, errChan), there would be no channel readers left from Handle and sending on the channels would block indefinitely with no readers. Since process would not return in this case, the channels would also not be closed.

I came up with the process2 as a solution, but I can't help thinking I'm doing something wrong, or there's a better way to handle this.

func process2(ctx context.Context, r *Req, resChan chan<- Response, errChan chan<- error) {
    defer close(errChan)
    defer close(resChan)

    err := doSomeWork()
    select {
    case <-ctx.Done():
        return
    default:
        if err != nil {
            errChan <- err
            return
        }
    }

    err = doSomeMoreWork()
    select {
    case <-ctx.Done():
        return
    default:
        if err != nil {
            errChan <- err
            return
        }
    }

    res := Response{}
    select{
    case <-ctx.Done():
        return
    default:
        resChan <- res
    }
}

This approach makes sure that each time a channel send is attempted, first the context is checked for having been completed or cancelled. If it was, then it does not attempt the send and returns. I'm pretty sure this fixes any go routine leaking happening in the first process func.

Is there a better way? Maybe I have this all wrong.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 关于#Java#的问题,如何解决?
    • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
    • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
    • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
    • ¥15 cmd cl 0x000007b
    • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
    • ¥500 火焰左右视图、视差(基于双目相机)
    • ¥100 set_link_state
    • ¥15 虚幻5 UE美术毛发渲染
    • ¥15 CVRP 图论 物流运输优化