dpca31461 2016-12-20 02:04
浏览 36
已采纳

匿名函数似乎未在Go例程中执行

I have the following code. Pay special attention to the anonymous function:

func saveMatterNodes(matterId int, nodes []doculaw.LitigationNode) (bool, error) {

    var (
        err  error
        resp *http.Response
    )

    // Do this in multiple threads
    for _, node := range nodes {
        fmt.Println("in loops")
        go func() {
            postValues := doculaw.LitigationNode{
                Name:        node.Name,
                Description: node.Description,
                Days:        node.Days,
                Date:        node.Date,
                IsFinalStep: false,
                Completed:   false,
                Matter:      matterId}

            b := new(bytes.Buffer)
            json.NewEncoder(b).Encode(postValues)
            resp, err = http.Post("http://127.0.0.1:8001/matterNode/", "application/json", b)
            io.Copy(os.Stdout, resp.Body)

            fmt.Println("Respone from http post", resp)
            if err != nil {
                fmt.Println(err)
            }
        }()

    }

    if err != nil {
        return false, err
    } else {
        return true, nil
    }

}

If I remove the go func() {}() part and just leave the code in between it seems to execute fine but the moment I add it back it does not execute. Any idea why that is? I initially thought maybe because it's executing on a different thread but this doesn't seem to be the case as I can see on my webservice access logs that it is not executing.

  • 写回答

1条回答 默认 最新

  • doulian4467 2016-12-20 02:26
    关注

    I think this behaviour is because function never yields back to main thread ( After you launch goroutines, there is no construct in program to wait for them to finish their work). Use of channels, IO operations, sync.WaitGroup etc can yield control back to the main thread.

    You may want to try sync.WaitGroup

    Example: https://play.golang.org/p/Zwn0YBynl2

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

报告相同问题?

悬赏问题

  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体