dongmi19720408 2014-07-02 23:32
浏览 34
已采纳

并发如何与匿名函数一起工作? 走

I'm trying to loop through a list (e.g. sql rows) and fire go routines for each row. The issue is that the values passed to the function are not evaluated at the runtime so depending by how much time the function takes to execute it may use whatever value is on one of the next(s) rows instead the current one.

I'm aware that I could extract the function in a normal one and pass the arguments but I still want to share some global variables(to avoid many function arguments) thus the need to use an anonymous function. Still it's also confusing to me that the anonymous function takes variables from the environment while it's being executed because as far as I understand it is supposed to be executed in a separate routines just like & in unix programs, the communication being done only through channels.

The question is how do I make the anonymous function to receive a copy of vc and use it during runtime ?

package main

import "fmt"
import "time"


type mystruct struct {
    i int
    s string
}

func main() {

    vc := mystruct{}
    vc.i = 1
    vc.s = "hi"
    gl := "this is global"
    for i := 1; i < 4; i++ {

    go func() {
        vc.i++
        time.Sleep(1 * time.Second)

        fmt.Printf("row specific is %v, global is %v", vc, gl)
    }()

    }
    time.Sleep(2 * time.Second)

}

Play here

  • 写回答

3条回答 默认 最新

  • dsfasdfsda234234 2014-07-03 11:35
    关注

    I honestly don't understand what you're trying to achieve, however, if your only goal is to make a copy of the variable, you can just pass it to the go func like this:

    for i := 1; i < 4; i++ {
        go func(vc mystruct) {
            vc.i++
            //time.Sleep(1 * time.Second)
    
            fmt.Printf("row specific is %v, global is %v
    ", vc, gl)
        }(vc)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 什么设备可以研究OFDM的60GHz毫米波信道模型
  • ¥15 不知道是该怎么引用多个函数片段
  • ¥15 爬取1-112页所有帖子的标题但是12页后要登录后才能 我使用selenium模拟登录 账号密码输入后 会报错 不知道怎么弄了
  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决
  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥50 分布式追踪trace异常问题