doujiao1984 2017-07-01 21:47
浏览 91
已采纳

Goroutine用指针在函数循环中覆盖了值?

I have just started playing with Go and stumbled upon problem how the pointers are handled in this language.

I have such code and can`t figure out how to fix it to get the correct response.

Changing func (me *Str) Start() to func (me Str) Start() fixes the problem, but I need this as reference to write this structure (it will have channel in it).

Sample code (https://play.golang.org/p/EsPejyCrX7):

package main

import (
    "fmt"
    "sync"
)

var wg1 sync.WaitGroup

type Str struct {
    id int
}

func (me *Str) Start() {
    wg1.Add(1)
    fmt.Println("F1 ", me)
    go me.startFn()
}

func (me *Str) startFn() {
    defer wg1.Done()
    fmt.Println("F2 ", me)
}

func main() {
    Fl2 := []Str{
        {1},
        {2},
        {3},
    }

    for _, fl := range Fl2 {
        fl.Start()
    }
    wg1.Wait()
}

Response:

F1  &{1}
F1  &{2}
F1  &{3}
F2  &{3}
F2  &{3}
F2  &{3}

Expected response (F2 can be random):

F1  &{1}
F1  &{2}
F1  &{3}
F2  &{3}
F2  &{2}
F2  &{1}
  • 写回答

1条回答 默认 最新

  • duancao1951 2017-07-01 21:54
    关注

    Using goroutines on loop iterator variables is a common mistake.

    Call .Start on the element of Fl2 by the range index, instead of the range value (playground):

    for i := range Fl2 {
        Fl2[i].Start()
    }
    

    However, the output might still not become exactly as you expect, due to the scheduling of the goroutines, for example it might be like this:

    F1  &{1}
    F1  &{2}
    F1  &{3}
    F2  &{3}
    F2  &{1}
    F2  &{2}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 wpf界面一直接收PLC给过来的信号,导致UI界面操作起来会卡顿
  • ¥15 init i2c:2 freq:100000[MAIXPY]: find ov2640[MAIXPY]: find ov sensor是main文件哪里有问题吗
  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了