我在我的项目中使用goroutines,我想将值赋给struct字段,但我不知道如何将通过使用mongodb quires获得的值赋给我正在显示我的结构和查询的struct字段。
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结构吗?
发布于 2019-01-31 17:36:51
在Go中,没有值对并发读写(从多个goroutines)是安全的。您必须同步访问。
可以使用sync.Mutex或sync.RWMutex保护从多个goroutine读取和写入变量,但在您的示例中,还涉及到其他事情:您应该等待两个启动的goroutine完成。为此,首选的解决方案是sync.WaitGroup。
由于这两个goroutine编写了一个结构的两个不同字段(它们充当两个不同的变量),因此它们不必彼此同步(请参阅此处的更多信息:Can I concurrently write different slice elements)。这意味着使用sync.WaitGroup就足够了。
以下是如何使其安全和正确的方法:
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?
发布于 2019-01-31 17:37:56
您可以在WaitGroup中使用sync包,示例如下:
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)
}输出:
Before {One: Two:}
After {One:foo Two:bar}https://stackoverflow.com/questions/54457213
复制相似问题