首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在go例程运行时为struct赋值?

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

Stack Overflow用户
提问于 2019-01-31 17:24:17
回答 2查看 1.6K关注 0票数 1

我在我的项目中使用goroutines,我想将值赋给struct字段,但我不知道如何将通过使用mongodb quires获得的值赋给我正在显示我的结构和查询的struct字段。

代码语言:javascript
复制
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
}

你能帮我把所有的值赋给AppLoadNew结构吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-01-31 17:36:51

在Go中,没有值对并发读写(从多个goroutines)是安全的。您必须同步访问。

可以使用sync.Mutexsync.RWMutex保护从多个goroutine读取和写入变量,但在您的示例中,还涉及到其他事情:您应该等待两个启动的goroutine完成。为此,首选的解决方案是sync.WaitGroup

由于这两个goroutine编写了一个结构的两个不同字段(它们充当两个不同的变量),因此它们不必彼此同步(请参阅此处的更多信息:Can I concurrently write different slice elements)。这意味着使用sync.WaitGroup就足够了。

以下是如何使其安全和正确的方法:

代码语言:javascript
复制
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)
}

请看Go Playground上的一个(稍微修改过的)工作示例。

请参阅相关/类似问题:

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

票数 3
EN

Stack Overflow用户

发布于 2019-01-31 17:37:56

您可以在WaitGroup中使用sync包,示例如下:

代码语言:javascript
复制
package main

import (
    "fmt"
    "sync"
    "time"
)

type Foo struct {
    One string
    Two string
}

func main() {
    f := Foo{}
    var wg sync.WaitGroup

    wg.Add(1)
    go func() {
        defer wg.Done()
        // Perform long calculations
        <-time.After(time.Second * 1)
        f.One = "foo"
    }()

    wg.Add(1)
    go func() {
        defer wg.Done()
        // Perform long calculations
        <-time.After(time.Second * 2)
        f.Two = "bar"

    }()

    fmt.Printf("Before %+v\n", f)
    wg.Wait()
    fmt.Printf("After %+v\n", f)
}

输出:

代码语言:javascript
复制
Before {One: Two:}
After {One:foo Two:bar}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54457213

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档