dongnunai3125 2016-09-13 16:14
浏览 191
已采纳

Golang匿名函数循环-值作为参数传递的问题

I had read various pages such as https://github.com/golang/go/wiki/CommonMistakes which outlined the issues with using closures and goroutines in a loop. As such I wrote my original loops as follows:

for outstanding < threads {
    ttl += 1;
    outstanding += 1;
    go func (ttl int, results chan Result) {
        results <- pw.SendTTL(ttl, dest)
        results <- pw.Recv(3)
    }(ttl, results)
}

Passing the changing TTL as an argument to the anonymous function. I ended up getting a random assortment of values over the range. Say if I was expecting 1-5 I'd get a couple 1's, a couple 3's, maybe a 4.

So I tried the following, in case there was something about specifically using the variable instantiated by the loop. Yes I know I'm sort of abusing the for loop here...

for i := ttl; outstanding < threads; i++ {
    go func (ttl int, results chan Result) {
        results <- pw.SendTTL(ttl, dest)
        results <- pw.Recv(3)
    }(i, results)
    outstanding++;
}

No joy. Same experience.

I also tried the other suggested option where you use a local variable in the loop, and use that within the closure. Same experience.

What am I doing wrong here? What boat did I miss?

  • 写回答

1条回答 默认 最新

  • dsndm82062 2016-09-13 18:03
    关注

    In writing out the requested example I think I realized what my problem was. The various go routines were clobbering each others TTL settings when attempting to share the socket.

    Question withdrawn ;)

    Edit: To clarify, the right value was in fact being passed to the routines in either case. It was an underlying sharing of resources that was the problem.

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

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀