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

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

报告相同问题?

悬赏问题

  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥15 键盘指令混乱情况下的启动盘系统重装