async

package module
v0.6.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 14, 2023 License: MIT Imports: 9 Imported by: 20

README


Async is a synchronization and asynchronous computation package for Go.

Overview

  • ConcurrentMap - Implements the generic async.Map interface in a thread-safe manner by delegating load/store operations to the underlying sync.Map.
  • Future - A placeholder object for a value that may not yet exist.
  • Promise - While futures are defined as a type of read-only placeholder object created for a result which doesn’t yet exist, a promise can be thought of as a writable, single-assignment container, which completes a future.
  • Task - A data type for controlling possibly lazy and asynchronous computations.
  • Once - An object similar to sync.Once having the Do method taking f func() (T, error) and returning (T, error).
  • WaitGroupContext - A WaitGroup with the context.Context support for graceful unblocking.
  • Reentrant Lock - Mutex that allows goroutines to enter into the lock on a resource more than once.
  • Optimistic Lock - Mutex that allows optimistic reading. Could be retried or switched to RLock in case of failure. Significantly improves performance in case of frequent reads and short writes. See benchmarks.

Examples

Can be found in the examples directory/tests.

License

Licensed under the MIT License.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GoroutineID

func GoroutineID() (uint, error)

GoroutineID returns the current goroutine id.

Types

type ConcurrentMap added in v0.6.0

type ConcurrentMap[K comparable, V any] struct {
	// contains filtered or unexported fields
}

ConcurrentMap implements the async.Map interface in a thread-safe manner by delegating load/store operations to the underlying sync.Map. A ConcurrentMap must not be copied.

The sync.Map type is optimized for two common use cases: (1) when the entry for a given key is only ever written once but read many times, as in caches that only grow, or (2) when multiple goroutines read, write, and overwrite entries for disjoint sets of keys. In these two cases, use of a sync.Map may significantly reduce lock contention compared to a Go map paired with a separate sync.Mutex or sync.RWMutex.

func NewConcurrentMap added in v0.6.0

func NewConcurrentMap[K comparable, V any]() *ConcurrentMap[K, V]

NewConcurrentMap returns a new ConcurrentMap instance.

func (*ConcurrentMap[K, V]) Clear added in v0.6.0

func (cm *ConcurrentMap[K, V]) Clear()

Clear removes all of the mappings from this map.

func (*ConcurrentMap[K, V]) ComputeIfAbsent added in v0.6.0

func (cm *ConcurrentMap[K, V]) ComputeIfAbsent(key K, mappingFunction func(K) *V) *V

ComputeIfAbsent attempts to compute a value using the given mapping function and enters it into the map, if the specified key is not already associated with a value.

func (*ConcurrentMap[K, V]) ContainsKey added in v0.6.0

func (cm *ConcurrentMap[K, V]) ContainsKey(key K) bool

ContainsKey returns true if this map contains a mapping for the specified key.

func (*ConcurrentMap[K, V]) Get added in v0.6.0

func (cm *ConcurrentMap[K, V]) Get(key K) *V

Get returns the value to which the specified key is mapped, or nil if this map contains no mapping for the key.

func (*ConcurrentMap[K, V]) GetOrDefault added in v0.6.0

func (cm *ConcurrentMap[K, V]) GetOrDefault(key K, defaultValue *V) *V

GetOrDefault returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key.

func (*ConcurrentMap[K, V]) IsEmpty added in v0.6.0

func (cm *ConcurrentMap[K, V]) IsEmpty() bool

IsEmpty returns true if this map contains no key-value mappings.

func (*ConcurrentMap[K, V]) KeySet added in v0.6.0

func (cm *ConcurrentMap[K, V]) KeySet() []K

KeySet returns a slice of the keys contained in this map.

func (*ConcurrentMap[K, V]) Put added in v0.6.0

func (cm *ConcurrentMap[K, V]) Put(key K, value *V)

Put associates the specified value with the specified key in this map.

func (*ConcurrentMap[K, V]) Remove added in v0.6.0

func (cm *ConcurrentMap[K, V]) Remove(key K) *V

Remove removes the mapping for a key from this map if it is present, returning the previous value or nil if none.

func (*ConcurrentMap[K, V]) Size added in v0.6.0

func (cm *ConcurrentMap[K, V]) Size() int

Size returns the number of key-value mappings in this map.

func (*ConcurrentMap[K, V]) Values added in v0.6.0

func (cm *ConcurrentMap[K, V]) Values() []*V

Values returns a slice of the values contained in this map.

type Future

type Future[T any] interface {

	// Map creates a new Future by applying a function to the successful result of this Future.
	Map(func(T) (T, error)) Future[T]

	// FlatMap creates a new Future by applying a function to the successful result of
	// this Future.
	FlatMap(func(T) (Future[T], error)) Future[T]

	// Join blocks until the Future is completed and returns either a result or an error.
	Join() (T, error)

	// Get blocks for at most the given time duration for this Future to complete
	// and returns either a result or an error.
	Get(time.Duration) (T, error)

	// Recover handles any error that this Future might contain using a resolver function.
	Recover(func() (T, error)) Future[T]

	// RecoverWith handles any error that this Future might contain using another Future.
	RecoverWith(Future[T]) Future[T]
	// contains filtered or unexported methods
}

Future represents a value which may or may not currently be available, but will be available at some point, or an error if that value could not be made available.

func FutureFirstCompletedOf

func FutureFirstCompletedOf[T any](futures ...Future[T]) Future[T]

FutureFirstCompletedOf asynchronously returns a new Future to the result of the first Future in the list that is completed. This means no matter if it is completed as a success or as a failure.

func FutureSeq

func FutureSeq[T any](futures []Future[T]) Future[[]interface{}]

FutureSeq reduces many Futures into a single Future.

func FutureTimer

func FutureTimer[T any](d time.Duration) Future[T]

FutureTimer returns Future that will have been resolved after given duration; useful for FutureFirstCompletedOf for timeout purposes.

func NewFuture

func NewFuture[T any]() Future[T]

NewFuture returns a new Future.

type FutureImpl

type FutureImpl[T any] struct {
	// contains filtered or unexported fields
}

FutureImpl implements the Future interface.

func (*FutureImpl[T]) FlatMap

func (fut *FutureImpl[T]) FlatMap(f func(T) (Future[T], error)) Future[T]

FlatMap creates a new Future by applying a function to the successful result of this Future and returns the result of the function as a new Future.

func (*FutureImpl[T]) Get

func (fut *FutureImpl[T]) Get(timeout time.Duration) (T, error)

Get blocks for at most the given time duration for this Future to complete and returns either a result or an error.

func (*FutureImpl[T]) Join added in v0.5.0

func (fut *FutureImpl[T]) Join() (T, error)

Join blocks until the Future is completed and returns either a result or an error.

func (*FutureImpl[T]) Map

func (fut *FutureImpl[T]) Map(f func(T) (T, error)) Future[T]

Map creates a new Future by applying a function to the successful result of this Future and returns the result of the function as a new Future.

func (*FutureImpl[T]) Recover

func (fut *FutureImpl[T]) Recover(f func() (T, error)) Future[T]

Recover handles any error that this Future might contain using a given resolver function. Returns the result as a new Future.

func (*FutureImpl[T]) RecoverWith

func (fut *FutureImpl[T]) RecoverWith(rf Future[T]) Future[T]

RecoverWith handles any error that this Future might contain using another Future. Returns the result as a new Future.

type Map added in v0.6.0

type Map[K comparable, V any] interface {

	// Clear removes all of the mappings from this map.
	Clear()

	// ComputeIfAbsent attempts to compute a value using the given mapping
	// function and enters it into the map, if the specified key is not
	// already associated with a value.
	ComputeIfAbsent(key K, mappingFunction func(K) *V) *V

	// ContainsKey returns true if this map contains a mapping for the
	// specified key.
	ContainsKey(key K) bool

	// Get returns the value to which the specified key is mapped, or nil if
	// this map contains no mapping for the key.
	Get(key K) *V

	// GetOrDefault returns the value to which the specified key is mapped, or
	// defaultValue if this map contains no mapping for the key.
	GetOrDefault(key K, defaultValue *V) *V

	// IsEmpty returns true if this map contains no key-value mappings.
	IsEmpty() bool

	// KeySet returns a slice of the keys contained in this map.
	KeySet() []K

	// Put associates the specified value with the specified key in this map.
	Put(key K, value *V)

	// Remove removes the mapping for a key from this map if it is present,
	// returning the previous value or nil if none.
	Remove(key K) *V

	// Size returns the number of key-value mappings in this map.
	Size() int

	// Values returns a slice of the values contained in this map.
	Values() []*V
}

A Map is an object that maps keys to values.

type Once added in v0.6.0

type Once[T any] struct {
	// contains filtered or unexported fields
}

Once is an object that will execute the given function exactly once. Any subsequent call will return the previous result.

func (*Once[T]) Do added in v0.6.0

func (o *Once[T]) Do(f func() (T, error)) (T, error)

Do calls the function f if and only if Do is being called for the first time for this instance of Once. In other words, given

var once Once

if once.Do(f) is called multiple times, only the first call will invoke f, even if f has a different value in each invocation. A new instance of Once is required for each function to execute.

The return values for each subsequent call will be the result of the first execution.

If f panics, Do considers it to have returned; future calls of Do return without calling f

type OptimisticLock

type OptimisticLock struct {
	// contains filtered or unexported fields
}

OptimisticLock allows optimistic reading. Implements the Locker interface and is not reentrant.

func NewOptimisticLock

func NewOptimisticLock() *OptimisticLock

NewOptimisticLock returns a new OptimisticLock.

func (*OptimisticLock) Lock

func (o *OptimisticLock) Lock()

Lock locks the resource for write.

func (*OptimisticLock) OptLock

func (o *OptimisticLock) OptLock() int64

OptLock returns the stamp to be verified on OptUnlock.

func (*OptimisticLock) OptUnlock

func (o *OptimisticLock) OptUnlock(stamp int64) bool

OptUnlock returns true if the lock has not been acquired in write mode since obtaining a given stamp. Retry or switch to RLock in case of failure.

func (*OptimisticLock) RLock

func (o *OptimisticLock) RLock()

RLock locks the resource for read.

func (*OptimisticLock) RUnlock

func (o *OptimisticLock) RUnlock()

RUnlock unlocks the resource after read.

func (*OptimisticLock) Unlock

func (o *OptimisticLock) Unlock()

Unlock unlocks the resource after write.

type Promise

type Promise[T any] interface {

	// Success completes the underlying Future with a value.
	Success(T)

	// Failure fails the underlying Future with an error.
	Failure(error)

	// Future returns the underlying Future.
	Future() Future[T]
}

Promise represents a writable, single-assignment container, which completes a Future.

func NewPromise

func NewPromise[T any]() Promise[T]

NewPromise returns a new PromiseImpl.

type PromiseImpl

type PromiseImpl[T any] struct {
	sync.Mutex
	// contains filtered or unexported fields
}

PromiseImpl implements the Promise interface.

func (*PromiseImpl[T]) Failure

func (p *PromiseImpl[T]) Failure(err error)

Failure fails the underlying Future with a given error.

func (*PromiseImpl[T]) Future

func (p *PromiseImpl[T]) Future() Future[T]

Future returns the underlying Future.

func (*PromiseImpl[T]) Success

func (p *PromiseImpl[T]) Success(value T)

Success completes the underlying Future with a given value.

type ReentrantLock

type ReentrantLock struct {
	// contains filtered or unexported fields
}

ReentrantLock allows goroutines to enter the lock more than once.

func NewReentrantLock

func NewReentrantLock() *ReentrantLock

NewReentrantLock returns a new ReentrantLock.

func (*ReentrantLock) Lock

func (r *ReentrantLock) Lock()

Lock locks the resource. Panics if the GoroutineID call returns an error.

func (*ReentrantLock) Unlock

func (r *ReentrantLock) Unlock()

Unlock unlocks the resource. Panics on trying to unlock the unlocked lock.

type Task added in v0.4.0

type Task[T any] struct {
	// contains filtered or unexported fields
}

Task is a data type for controlling possibly lazy & asynchronous computations.

func NewTask added in v0.4.0

func NewTask[T any](taskFunc func() (T, error)) *Task[T]

NewTask returns a new Task.

func (*Task[T]) Call added in v0.4.0

func (task *Task[T]) Call() Future[T]

Call executes the Task and returns a Future.

type WaitGroupContext added in v0.5.0

type WaitGroupContext struct {
	// contains filtered or unexported fields
}

A WaitGroupContext waits for a collection of goroutines to finish. The main goroutine calls Add to set the number of goroutines to wait for. Then each of the goroutines runs and calls Done when finished. At the same time, Wait can be used to block until all goroutines have finished or the given context is done.

func NewWaitGroupContext added in v0.5.0

func NewWaitGroupContext(ctx context.Context) *WaitGroupContext

NewWaitGroupContext returns a new WaitGroupContext with Context ctx.

func (*WaitGroupContext) Add added in v0.5.0

func (wgc *WaitGroupContext) Add(delta int)

Add adds delta, which may be negative, to the WaitGroupContext counter. If the counter becomes zero, all goroutines blocked on Wait are released. If the counter goes negative, Add panics.

func (*WaitGroupContext) Done added in v0.5.0

func (wgc *WaitGroupContext) Done()

Done decrements the WaitGroupContext counter by one.

func (*WaitGroupContext) Wait added in v0.5.0

func (wgc *WaitGroupContext) Wait()

Wait blocks until the wait group counter is zero or ctx is done.

Directories

Path Synopsis
examples
future command
goroutine command
internal

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL