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()))
}
Output:
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Container ¶
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 ¶
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.