doubeng9407 2019-01-31 09:24
浏览 234
已采纳

在go例程运行时如何为struct赋值?

I'm using goroutines in my project and I want to to assign the values to the struct fields but I don't know that how I will assign the values get by using mongodb quires to the struct fields I'm showing my struct and the query too.

type AppLoadNew struct{
    StripeTestKey      string                   `json:"stripe_test_key" bson:"stripe_test_key,omitempty"`
    Locations          []Locations              `json:"location" bson:"location,omitempty"`
}

type Locations struct{
   Id int `json:"_id" bson:"_id"`
   Location  string `json:"location" bson:"location"`
}

func GoRoutine(){
   values := AppLoadNew{}
   go func() {
      data, err := GetStripeTestKey(bson.M{"is_default": true})
      if err == nil {
        values.StripeTestKey := data.TestStripePublishKey
      }
  }()
  go func() {
      location, err := GetFormLocation(bson.M{"is_default": true})
      if err == nil {
        values.Locations := location
      }
  }()
  fmt.Println(values) // Here it will nothing
  // empty
}

Can you please help me that I will assign all the values to the AppLoadNew struct.

  • 写回答

2条回答 默认 最新

  • dongyue1988 2019-01-31 09:36
    关注

    In Go no value is safe for concurrent read and write (from multiple goroutines). You must synchronize access.

    Reading and writing variables from multiple goroutines can be protected using sync.Mutex or sync.RWMutex, but in your case there is something else involved: you should wait for the 2 launched goroutines to complete. For that, the go-to solution is sync.WaitGroup.

    And since the 2 goroutines write 2 different fields of a struct (which act as 2 distinct variables), they don't have to be synchronized to each other (see more on this here: Can I concurrently write different slice elements). Which means using a sync.WaitGroup is sufficient.

    This is how you can make it safe and correct:

    func GoRoutine() {
        values := AppLoadNew{}
    
        wg := &sync.WaitGroup{}
    
        wg.Add(1)
        go func() {
            defer wg.Done()
            data, err := GetStripeTestKey(bson.M{"is_default": true})
            if err == nil {
                values.StripeTestKey = data.StripeTestKey
            }
        }()
    
        wg.Add(1)
        go func() {
            defer wg.Done()
            location, err := GetFormLocation(bson.M{"is_default": true})
            if err == nil {
                values.Locations = location
            }
        }()
    
        wg.Wait()
        fmt.Println(values)
    }
    

    See a (slightly modified) working example on the Go Playground.

    See related / similar questions:

    Reading values from a different thread

    golang struct concurrent read and write without Lock is also running ok?

    How to make a variable thread-safe

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?