github.com/OpenFlowLabs/moby@v17.12.1-ce-rc2+incompatible/pkg/locker/README.md (about) 1 Locker 2 ===== 3 4 locker provides a mechanism for creating finer-grained locking to help 5 free up more global locks to handle other tasks. 6 7 The implementation looks close to a sync.Mutex, however, the user must provide a 8 reference to use to refer to the underlying lock when locking and unlocking, 9 and unlock may generate an error. 10 11 If a lock with a given name does not exist when `Lock` is called, one is 12 created. 13 Lock references are automatically cleaned up on `Unlock` if nothing else is 14 waiting for the lock. 15 16 17 ## Usage 18 19 ```go 20 package important 21 22 import ( 23 "sync" 24 "time" 25 26 "github.com/docker/docker/pkg/locker" 27 ) 28 29 type important struct { 30 locks *locker.Locker 31 data map[string]interface{} 32 mu sync.Mutex 33 } 34 35 func (i *important) Get(name string) interface{} { 36 i.locks.Lock(name) 37 defer i.locks.Unlock(name) 38 return i.data[name] 39 } 40 41 func (i *important) Create(name string, data interface{}) { 42 i.locks.Lock(name) 43 defer i.locks.Unlock(name) 44 45 i.createImportant(data) 46 47 i.mu.Lock() 48 i.data[name] = data 49 i.mu.Unlock() 50 } 51 52 func (i *important) createImportant(data interface{}) { 53 time.Sleep(10 * time.Second) 54 } 55 ``` 56 57 For functions dealing with a given name, always lock at the beginning of the 58 function (or before doing anything with the underlying state), this ensures any 59 other function that is dealing with the same name will block. 60 61 When needing to modify the underlying data, use the global lock to ensure nothing 62 else is modifying it at the same time. 63 Since name lock is already in place, no reads will occur while the modification 64 is being performed. 65