concurrent

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Jun 20, 2025 License: MIT Imports: 3 Imported by: 1

Documentation

Overview

Package concurrent provides common concurrent safe types.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Cache

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

Cache provides a very simple in-memory cache which is based simply on a map and sync.Mutex.

func (*Cache[K, V]) Get

func (c *Cache[K, V]) Get(key K) (V, bool)

Get retrieves the value for the given key. If the key does not exist in the cache, then the zero value for V will be returned along with false.

func (*Cache[K, V]) GetOrNew

func (c *Cache[K, V]) GetOrNew(key K, f func() (V, error)) (V, error)

GetOrNew retrieves the value for the given key. If the key does not exist in the cache, then the given function will be called to get the value. If the given function succeeds, then the returned value will be placed in the cache before being returned.

func (*Cache[K, V]) Put

func (c *Cache[K, V]) Put(key K, value V)

Put places the key value pair into the cache. It will override any previously cached value.

type LazyGroup

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

LazyGroup is a collection of goroutines. The goroutines are not created until LazyGroup.Wait is called. A zero LazyGroup is valid, has no limit on the number of active goroutines.

Example
var computeGroup LazyGroup
partialSumCh := make(chan int)
for i := range 10 {
	computeGroup.Go(func(ctx context.Context) error {
		var total int
		for j := range 100000 {
			total += (j + 1) + i*100000
		}

		select {
		case <-ctx.Done():
			return ctx.Err()
		case partialSumCh <- total:
		}
		return nil
	})
}

var sumGroup LazyGroup
sumGroup.Go(func(ctx context.Context) error {
	defer close(partialSumCh)
	return computeGroup.Wait(ctx)
})
sumGroup.Go(func(ctx context.Context) error {
	var total int
	for {
		select {
		case <-ctx.Done():
			return ctx.Err()
		case partialSum, ok := <-partialSumCh:
			if !ok {
				fmt.Println(total)
				return nil
			}

			total += partialSum
		}
	}
})

err := sumGroup.Wait(context.Background())
if err != nil {
	fmt.Println(err)
	return
}
Output:

500000500000

func (*LazyGroup) Go

func (g *LazyGroup) Go(f func(context.Context) error)

Go registers the given func to be ran on its own goroutine once LazyGroup.Wait is called.

func (*LazyGroup) Wait

func (g *LazyGroup) Wait(ctx context.Context) error

Wait runs all registered funcs in their own goroutines and waits for all of them to complete. Wait will returns the first error to be returned by any of the funcs which returned a non-nil error.

Jump to

Keyboard shortcuts

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