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条)

报告相同问题?

悬赏问题

  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?