...

Text file src/github.com/moby/locker/README.md

Documentation: github.com/moby/locker

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

View as plain text