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

报告相同问题?

悬赏问题

  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化