Fix mutex being copied & wrong mutex key

The get `getOrCreateMutex` function copies mutexes which the golang docs specifically tell us not to do: https://golang.org/pkg/sync/#Mutex

Also, the delete function was creating a mutex for the resource, not the collection.
This commit is contained in:
Adam Bouqdib 2017-03-27 15:08:01 +02:00 committed by GitHub
parent e8f97ab321
commit 9cdf35aaef
1 changed files with 5 additions and 5 deletions

View File

@ -31,7 +31,7 @@ type (
// transactions, and provides log output // transactions, and provides log output
Driver struct { Driver struct {
mutex sync.Mutex mutex sync.Mutex
mutexes map[string]sync.Mutex mutexes map[string]*sync.Mutex
dir string // the directory where scribble will create the database dir string // the directory where scribble will create the database
log Logger // the logger scribble will log to log Logger // the logger scribble will log to
} }
@ -65,7 +65,7 @@ func New(dir string, options *Options) (*Driver, error) {
// //
driver := Driver{ driver := Driver{
dir: dir, dir: dir,
mutexes: make(map[string]sync.Mutex), mutexes: make(map[string]*sync.Mutex),
log: opts.Logger, log: opts.Logger,
} }
@ -199,7 +199,7 @@ func (d *Driver) ReadAll(collection string) ([]string, error) {
func (d *Driver) Delete(collection, resource string) error { func (d *Driver) Delete(collection, resource string) error {
path := filepath.Join(collection, resource) path := filepath.Join(collection, resource)
// //
mutex := d.getOrCreateMutex(path) mutex := d.getOrCreateMutex(collection)
mutex.Lock() mutex.Lock()
defer mutex.Unlock() defer mutex.Unlock()
@ -237,7 +237,7 @@ func stat(path string) (fi os.FileInfo, err error) {
// getOrCreateMutex creates a new collection specific mutex any time a collection // getOrCreateMutex creates a new collection specific mutex any time a collection
// is being modfied to avoid unsafe operations // is being modfied to avoid unsafe operations
func (d *Driver) getOrCreateMutex(collection string) sync.Mutex { func (d *Driver) getOrCreateMutex(collection string) *sync.Mutex {
d.mutex.Lock() d.mutex.Lock()
defer d.mutex.Unlock() defer d.mutex.Unlock()
@ -246,7 +246,7 @@ func (d *Driver) getOrCreateMutex(collection string) sync.Mutex {
// if the mutex doesn't exist make it // if the mutex doesn't exist make it
if !ok { if !ok {
m = sync.Mutex{} m = &sync.Mutex{}
d.mutexes[collection] = m d.mutexes[collection] = m
} }