I am trying to understand whether Mongo locks Go objects.
The first function works fine with the json encoder, however the second function fails fatal error: sync: Unlock of unlocked RWMutex
. Is this because mongo.Find is already trying to lock/unlock the state object? Do I need to externally handle race competition for my go objects or does MGO take care of it? I tried reading the source code but I haven't been able to reach a conclusion.
Any would be much appreciated!
import (
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
"io"
"sync"
"encoding/json"
)
type ApplicationState struct {
FileStates map[string]FileState `json:"fileStates" bson:"fileStates"`
lock sync.RWMutex `json:"-" bson:"-"`
}
func (state *ApplicationState) ReadState(reader io.Reader) error {
state.lock.Lock()
defer state.lock.Unlock()
return json.NewDecoder(reader).Decode(state)}
func (state *ApplicationState) ReadStateMGO(c *mgo.Collection) error {
state.lock.Lock()
defer state.lock.Unlock()
return c.Find( bson.M{} ).Select( bson.M{"_id": 0} ).One(state)}
Note: to test it you can just replace the Filestate field with a string map.