Documentation
¶
Overview ¶
Package sync defines various functions useful with sync of any type.
Index ¶
- Constants
- func WithLock(lk sync.Locker, fn func())
- type EvictCallback
- type FixedPool
- func (p *FixedPool[E]) Cap() int
- func (p *FixedPool[E]) Emplace(x E)
- func (p *FixedPool[E]) Get() *FixedPoolElement[E]
- func (p *FixedPool[E]) GetContext(ctx context.Context) (*FixedPoolElement[E], error)
- func (p *FixedPool[E]) Init() *FixedPool[E]
- func (p *FixedPool[E]) Len() int
- func (p *FixedPool[E]) Put(x *FixedPoolElement[E]) (stored bool)
- func (p *FixedPool[E]) TryGet() *FixedPoolElement[E]
- func (p *FixedPool[E]) TryPut(x *FixedPoolElement[E]) (stored bool)
- type FixedPoolElement
- type LRU
- func (c *LRU[K, V]) Add(key K, value V) (evicted bool)
- func (c *LRU[K, V]) All() iter.Seq2[K, V]
- func (c *LRU[K, V]) Cap() int
- func (c *LRU[K, V]) CompareAndDelete(key K, old V) (deleted bool)
- func (c *LRU[K, V]) CompareAndSwap(key K, old, new V) (swapped bool)
- func (c *LRU[K, V]) Contains(key K) (ok bool)
- func (c *LRU[K, V]) Delete(key K)
- func (c *LRU[K, V]) Get(key K) (value V, ok bool)
- func (c *LRU[K, V]) GetOldest() (key K, value V, ok bool)
- func (c *LRU[K, V]) Init() *LRU[K, V]
- func (c *LRU[K, V]) Keys() iter.Seq[K]
- func (c *LRU[K, V]) Len() int
- func (c *LRU[K, V]) Load(key K) (value V, ok bool)
- func (c *LRU[K, V]) LoadAndDelete(key K) (value V, loaded bool)
- func (c *LRU[K, V]) LoadOrStore(key K, value V) (actual V, loaded bool)
- func (c *LRU[K, V]) Peek(key K) (value V, ok bool)
- func (c *LRU[K, V]) PeekAndDeleteOldest() (key K, value V, loaded bool)
- func (c *LRU[K, V]) PeekOldest() (key K, value V, ok bool)
- func (c *LRU[K, V]) Purge()
- func (c *LRU[K, V]) Range(f func(key K, value V) bool)
- func (c *LRU[K, V]) Remove(key K) (present bool)
- func (c *LRU[K, V]) RemoveOldest() (key K, value V, ok bool)
- func (c *LRU[K, V]) Resize(size int) (evicted int)
- func (c *LRU[K, V]) SetEvictCallback(onEvict EvictCallback[K, V]) *LRU[K, V]
- func (c *LRU[K, V]) SetEvictCallbackFunc(onEvict func(key K, value V)) *LRU[K, V]
- func (c *LRU[K, V]) Store(key K, value V)
- func (c *LRU[K, V]) Swap(key K, value V) (previous V, loaded bool)
- func (c *LRU[K, V]) Values() iter.Seq[V]
- type Map
- func (m *Map[K, V]) Clear()
- func (m *Map[K, V]) CompareAndDelete(key K, old V) (deleted bool)
- func (m *Map[K, V]) CompareAndSwap(key K, old, new V) (swapped bool)
- func (m *Map[K, V]) Delete(key K)
- func (m *Map[K, V]) Load(key K) (V, bool)
- func (m *Map[K, V]) LoadAndDelete(key K) (value V, loaded bool)
- func (m *Map[K, V]) LoadOrStore(key K, value V) (V, bool)
- func (m *Map[K, V]) Range(f func(key K, value V) bool)
- func (m *Map[K, V]) Store(key K, value V)
- func (m *Map[K, V]) Swap(key K, value V) (previous V, loaded bool)
- type Pool
Examples ¶
Constants ¶
const ( UnlimitedResident = -1 UnlimitedCapacity = 0 )
Variables ¶
This section is empty.
Functions ¶
Types ¶
type EvictCallback ¶
type EvictCallback[K comparable, V any] lru.EvictCallback[K, V]
EvictCallback is used to get a callback when a cache entry is evicted type EvictCallback[K comparable, V any] func(key K, value V)
type FixedPool ¶ added in v1.2.54
type FixedPool[E any] struct { // New optionally specifies a function to generate // a value when Get would otherwise return nil. // It may not be changed concurrently with calls to Get. New func() E // MinResidentSize controls the minimum number of keep-alive items. items will be preallocated. MinResidentSize int // MaxResidentSize controls the maximum number of keep-alive items. Negative means no limit. MaxResidentSize int // MaxCapacity controls the maximum number of allocated items. Zero means no limit. MaxCapacity int // contains filtered or unexported fields }
FixedPool is a set of resident and temporary items that may be individually saved and retrieved.
Any item stored in the Pool may be removed automatically at any time without notification. If the Pool holds the only reference when this happens, the item might be deallocated.
A Pool is safe for use by multiple goroutines simultaneously.
func NewCachedPool ¶ added in v1.2.54
NewCachedPool Creates a pool that creates new items as needed, but will reuse previously constructed items when they are available. the pool will reuse previously constructed items and items will never be dropped.
Example ¶
package main import ( "bytes" "fmt" "time" sync_ "github.com/searKing/golang/go/exp/sync" ) var bufCachedPool = sync_.NewCachedPool[*bytes.Buffer](func() *bytes.Buffer { fmt.Println("allocating new buffer") return new(bytes.Buffer) }) // timeNow is a fake version of time.Now for tests. func timeNow() time.Time { return time.Unix(1136214245, 0) } func Log(bufPool *sync_.FixedPool[*bytes.Buffer], key, val string) { be := bufPool.Get() { b := be.Value b.Reset() b.WriteString(timeNow().UTC().Format(time.RFC3339)) b.WriteByte(' ') b.WriteString(key) b.WriteByte('=') b.WriteString(val) fmt.Println(b.String()) } bufPool.Put(be) } func main() { Log(bufCachedPool, "path", "/search?q=flowers") Log(bufCachedPool, "path", "/search?q=vegetables") }
Output: allocating new buffer 2006-01-02T15:04:05Z path=/search?q=flowers 2006-01-02T15:04:05Z path=/search?q=vegetables
func NewFixedPool ¶ added in v1.2.54
NewFixedPool returns an initialized fixed pool. resident controls the maximum number of keep-alive items. Negative means no limit. cap controls the maximum number of allocated items. Zero means no limit.
Example ¶
package main import ( "bytes" "fmt" "time" sync_ "github.com/searKing/golang/go/exp/sync" ) var bufFixedPool = sync_.NewFixedPool[*bytes.Buffer](func() *bytes.Buffer { fmt.Println("allocating new buffer") return new(bytes.Buffer) }, 1) // timeNow is a fake version of time.Now for tests. func timeNow() time.Time { return time.Unix(1136214245, 0) } func Log(bufPool *sync_.FixedPool[*bytes.Buffer], key, val string) { be := bufPool.Get() { b := be.Value b.Reset() b.WriteString(timeNow().UTC().Format(time.RFC3339)) b.WriteByte(' ') b.WriteString(key) b.WriteByte('=') b.WriteString(val) fmt.Println(b.String()) } bufPool.Put(be) } func main() { Log(bufFixedPool, "path", "/search?q=flowers") Log(bufFixedPool, "path", "/search?q=vegetables") }
Output: 2006-01-02T15:04:05Z path=/search?q=flowers 2006-01-02T15:04:05Z path=/search?q=vegetables
func NewTempPool ¶ added in v1.2.54
NewTempPool Creates a pool that creates new items as needed, but will be dropped at second GC if only referenced by the pool self. the pool will reuse previously constructed items when they are available and not dropped.
Example ¶
package main import ( "bytes" "fmt" "time" sync_ "github.com/searKing/golang/go/exp/sync" ) var bufTempPool = sync_.NewTempPool[*bytes.Buffer](nil) // timeNow is a fake version of time.Now for tests. func timeNow() time.Time { return time.Unix(1136214245, 0) } func Log(bufPool *sync_.FixedPool[*bytes.Buffer], key, val string) { be := bufPool.Get() { b := be.Value b.Reset() b.WriteString(timeNow().UTC().Format(time.RFC3339)) b.WriteByte(' ') b.WriteString(key) b.WriteByte('=') b.WriteString(val) fmt.Println(b.String()) } bufPool.Put(be) } func main() { bufTempPool.Emplace(new(bytes.Buffer)) Log(bufTempPool, "path", "/search?q=flowers") Log(bufTempPool, "path", "/search?q=vegetables") }
Output: 2006-01-02T15:04:05Z path=/search?q=flowers 2006-01-02T15:04:05Z path=/search?q=vegetables
func (*FixedPool[E]) Cap ¶ added in v1.2.54
Cap returns the capacity of pool, that is object len allocated The complexity is O(1).
func (*FixedPool[E]) Emplace ¶ added in v1.2.54
func (p *FixedPool[E]) Emplace(x E)
Emplace adds x to the pool. NOTE: Emplace may break through the len and cap boundaries, as x be allocated already.
func (*FixedPool[E]) Get ¶ added in v1.2.54
func (p *FixedPool[E]) Get() *FixedPoolElement[E]
Get selects an arbitrary item from the Pool, removes it from the Pool, and returns it to the caller. Get may choose to ignore the pool and treat it as empty. Callers should not assume any relation between values passed to Put and the values returned by Get.
If Get would otherwise return nil and p.New is non-nil, Get returns the result of calling p.New.
Get uses context.Background internally; to specify the context, use GetContext.
func (*FixedPool[E]) GetContext ¶ added in v1.2.54
func (p *FixedPool[E]) GetContext(ctx context.Context) (*FixedPoolElement[E], error)
GetContext selects an arbitrary item from the Pool, removes it from the Pool, and returns it to the caller. Get may choose to ignore the pool and treat it as empty. Callers should not assume any relation between values passed to Put and the values returned by Get.
If GetContext would otherwise return nil and p.New is non-nil, Get returns the result of calling p.New.
func (*FixedPool[E]) Len ¶ added in v1.2.54
Len returns the len of pool, that is object len idle, allocated and still in cache The complexity is O(1).
func (*FixedPool[E]) Put ¶ added in v1.2.54
func (p *FixedPool[E]) Put(x *FixedPoolElement[E]) (stored bool)
Put adds x to the pool.
func (*FixedPool[E]) TryGet ¶ added in v1.2.54
func (p *FixedPool[E]) TryGet() *FixedPoolElement[E]
func (*FixedPool[E]) TryPut ¶ added in v1.2.54
func (p *FixedPool[E]) TryPut(x *FixedPoolElement[E]) (stored bool)
TryPut adds x to the pool, .
type FixedPoolElement ¶ added in v1.2.54
type FixedPoolElement[E any] struct { // The value stored with this element. Value E // contains filtered or unexported fields }
func (*FixedPoolElement[E]) Finalize ¶ added in v1.2.54
func (e *FixedPoolElement[E]) Finalize()
func (*FixedPoolElement[E]) Get ¶ added in v1.2.54
func (e *FixedPoolElement[E]) Get() E
type LRU ¶
type LRU[K comparable, V any] struct { // contains filtered or unexported fields }
LRU is like a Go map[K]V but implements a thread safe fixed size LRU cache. Loads, stores, and deletes run in amortized constant time. LRU is safe for use by multiple goroutines simultaneously. LRU must not be copied after first use.
func NewLRU ¶ added in v1.2.14
func NewLRU[K comparable, V any](size int) *LRU[K, V]
NewLRU constructs an LRU of the given size
Example ¶
package main import ( "fmt" sync_ "github.com/searKing/golang/go/exp/sync" ) func main() { l := sync_.NewLRU[int, int](2) var evictCounter int l.SetEvictCallback(func(k int, v int) { evictCounter++ fmt.Printf("{%d,%d} evicted as oldest: %d\n", k, v, evictCounter) }) printAll := func() { fmt.Printf("lru: ") first := true for k, v := range l.All() { if !first { fmt.Printf(", ") } first = false fmt.Printf("{%d,%d}", k, v) } fmt.Println() } l.Add(1, 1) l.Add(2, 2) l.Add(3, 3) // evict 1, that's the oldest printAll() fmt.Println("try to refresh {2,22}") l.Add(2, 22) // refresh 2; Now 3 is the oldest printAll() fmt.Println("try to remove oldest") l.RemoveOldest() // evict 2, that's the oldest printAll() fmt.Println("try to purge all elements") l.Purge() printAll() }
Output: {1,1} evicted as oldest: 1 lru: {2,2}, {3,3} try to refresh {2,22} lru: {3,3}, {2,22} try to remove oldest {3,3} evicted as oldest: 2 lru: {2,22} try to purge all elements {2,22} evicted as oldest: 3 lru:
func (*LRU[K, V]) All ¶ added in v1.2.121
All is an iterator over sequences of key-value pairs in the cache, from oldest to newest. If c is empty, the sequence is empty: there is no empty key-value pairs in the sequence.
func (*LRU[K, V]) CompareAndDelete ¶ added in v1.2.116
CompareAndDelete deletes the entry for key if its value is equal to old. The old value must be of a comparable type.
If there is no current value for key in the map, CompareAndDelete returns false (even if the old value is the nil interface value).
func (*LRU[K, V]) CompareAndSwap ¶ added in v1.2.116
CompareAndSwap swaps the old and new values for key if the value stored in the map is equal to old. The old value must be of a comparable type.
func (*LRU[K, V]) Contains ¶
Contains checks if a key is in the cache, without updating the recent-ness or deleting it for being stale.
func (*LRU[K, V]) Delete ¶ added in v1.2.116
func (c *LRU[K, V]) Delete(key K)
Delete deletes the value for a key.
func (*LRU[K, V]) Get ¶
Get looks up a key's value from the cache, with updating the "recently used"-ness of the key.
func (*LRU[K, V]) Keys ¶
Keys returns an iterator that yields the keys in the cache, from oldest to newest. Without updating the "recently used"-ness of the key.
func (*LRU[K, V]) Load ¶ added in v1.2.116
Load returns the value stored in the cache for a key, or zero if no value is present. The ok result indicates whether value was found in the cache.
func (*LRU[K, V]) LoadAndDelete ¶ added in v1.2.116
LoadAndDelete deletes the value for a key, returning the previous value if any. The loaded result reports whether the key was present.
func (*LRU[K, V]) LoadOrStore ¶ added in v1.2.116
LoadOrStore returns the existing value for the key if present. Otherwise, it stores and returns the given value. The loaded result is true if the value was loaded, false if stored.
func (*LRU[K, V]) Peek ¶
Peek returns the key value (or undefined if not found) without updating the "recently used"-ness of the key.
func (*LRU[K, V]) PeekAndDeleteOldest ¶ added in v1.2.116
PeekAndDeleteOldest deletes the value for a key, returning the previous value if any. The loaded result reports whether the key was present.
func (*LRU[K, V]) PeekOldest ¶ added in v1.2.116
PeekOldest returns the value stored in the cache for the oldest entry, or zero if no value is present. The ok result indicates whether value was found in the cache. Without updating the "recently used"-ness of the key.
func (*LRU[K, V]) Range ¶ added in v1.2.116
Range calls f sequentially for each key and value present in the lru from oldest to newest. If f returns false, range stops the iteration. Without updating the "recently used"-ness of the key.
func (*LRU[K, V]) Remove ¶
Remove removes the provided key from the cache, returning if the key was contained.
func (*LRU[K, V]) RemoveOldest ¶
RemoveOldest removes the oldest item from the cache.
func (*LRU[K, V]) SetEvictCallback ¶
func (c *LRU[K, V]) SetEvictCallback(onEvict EvictCallback[K, V]) *LRU[K, V]
SetEvictCallback sets a callback when a cache entry is evicted
func (*LRU[K, V]) SetEvictCallbackFunc ¶ added in v1.2.54
SetEvictCallbackFunc sets a callback when a cache entry is evicted
Deprecated, use SetEvictCallback instead.
func (*LRU[K, V]) Store ¶ added in v1.2.116
func (c *LRU[K, V]) Store(key K, value V)
Store sets the value for a key.
type Map ¶ added in v1.2.123
type Map[K comparable, V any] struct { // contains filtered or unexported fields }
Map is a generic wrapper for sync.Map, it is safe for concurrent use by multiple goroutines without additional locking or coordination. Loads, stores, and deletes run in amortized constant time.
func (*Map[K, V]) Clear ¶ added in v1.2.123
func (m *Map[K, V]) Clear()
Clear deletes all the entries, resulting in an empty Map.
func (*Map[K, V]) CompareAndDelete ¶ added in v1.2.123
CompareAndDelete deletes the entry for key if its value is equal to old. The old value must be of a comparable type.
If there is no current value for key in the map, CompareAndDelete returns false (even if the old value is the nil interface value).
func (*Map[K, V]) CompareAndSwap ¶ added in v1.2.123
CompareAndSwap swaps the old and new values for key if the value stored in the map is equal to old. The old value must be of a comparable type.
func (*Map[K, V]) Delete ¶ added in v1.2.123
func (m *Map[K, V]) Delete(key K)
Delete deletes the value for a key.
func (*Map[K, V]) Load ¶ added in v1.2.123
Load returns the value stored in the map for a key, or nil if no value is present. The ok result indicates whether value was found in the map.
func (*Map[K, V]) LoadAndDelete ¶ added in v1.2.123
LoadAndDelete deletes the value for a key, returning the previous value if any. The loaded result reports whether the key was present.
func (*Map[K, V]) LoadOrStore ¶ added in v1.2.123
LoadOrStore returns the existing value for the key if present. Otherwise, it stores and returns the given value. The loaded result is true if the value was loaded, false if stored.
func (*Map[K, V]) Range ¶ added in v1.2.123
Range calls f sequentially for each key and value present in the map. If f returns false, range stops the iteration.
Range does not necessarily correspond to any consistent snapshot of the Map's contents: no key will be visited more than once, but if the value for any key is stored or deleted concurrently, Range may reflect any mapping for that key from any point during the Range call.
Range may be O(N) with the number of elements in the map even if f returns false after a constant number of calls.
type Pool ¶ added in v1.2.123
type Pool[E any] struct { // New optionally specifies a function to generate // a value when Get would otherwise return zero. // It may not be changed concurrently with calls to Get. New func() E // contains filtered or unexported fields }
Pool is generic format of Go sync.Pool, it is safe for concurrent use by multiple goroutines without additional locking or coordination. Loads, stores, and deletes run in amortized constant time.
func (*Pool[E]) Get ¶ added in v1.2.123
func (p *Pool[E]) Get() E
Get selects an arbitrary item from the Pool, removes it from the Pool, and returns it to the caller. Get may choose to ignore the pool and treat it as empty. Callers should not assume any relation between values passed to Pool.Put and the values returned by Get.
If Get would otherwise return zero and p.New is non-nil, Get returns the result of calling p.New.