occ

package module
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Aug 25, 2024 License: MIT Imports: 1 Imported by: 2 modules, 2 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

occ

Go Reference

Generic optimistic concurrent container for Go.

Documentation

Overview

Package occ provides generic optimistic concurrency wrapper for values which can be represented by a pointer and accessed or replaced with a new copy concurrently.

It is useful for implementation of lock-free concurrency on top of immutable data structures.

Example
package main

import (
	"fmt"
	"sync"

	"github.com/Snawoot/occ"
)

func main() {
	ctr := occ.Wrap(new(int))
	var wg sync.WaitGroup
	for i := 0; i < 10; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			ctr.Update(func(old *int) *int {
				res := *old + 1
				return &res
			})
		}()
	}
	wg.Wait()
	fmt.Printf("ctr = %d\n", *(ctr.Value()))
}

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Container

type Container[T any] atomic.Pointer[T]

Container uses optimistic concurrency control for access and update of pointer it wraps. Essentially it is just an atomic pointer with compare-and-set logic around updates, so concurrent writes will no get lost and colliding changes will be retried instead.

func Wrap

func Wrap[T any](ptr *T) *Container[T]

Wrap creates Container from a pointer to any type. This pointer should not be used directly after wrapping.

func (*Container[T]) Update

func (c *Container[T]) Update(txn func(oldValue *T) (newValue *T))

Update runs a transaction function txn which accepts old pointer value and returns new pointer value. txn function must not modify value referenced by an old pointer, instead it should return a new pointer with modified copy of old value.

func (*Container[T]) Value

func (c *Container[T]) Value() *T

Value returns snapshot of wrapped value.

Jump to

Keyboard shortcuts

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