Thread-safe collections and synchronization helpers for Go applications.
The module contains a root syncing package and a circuitbreaker subpackage.
- Go 1.26 or newer
- Installation
- Quick start
- Limit concurrent work
- Manage task lifetimes
- Rate limit calls
- Circuit breaker
- Other helpers
- Tests and CI
- License
go get go.osspkg.com/syncingImport the root package as go.osspkg.com/syncing. The circuit breaker is
available at go.osspkg.com/syncing/circuit-breaker.
Map and Slice provide concurrent-safe access to generic collections. Each
method is synchronized independently; use a lock or another coordination
primitive when several operations must form one atomic action.
package main
import (
"fmt"
"go.osspkg.com/syncing"
)
func main() {
cache := syncing.NewMap[string, int](16)
cache.Set("jobs", 3)
if count, ok := cache.Get("jobs"); ok {
fmt.Println("jobs:", count)
}
for key, value := range cache.Yield() {
fmt.Println(key, value)
}
items := syncing.NewSlice[string](4)
items.Append("first", "second")
for item := range items.Yield() {
fmt.Println("item:", item)
}
if item, ok := items.Pop(); ok {
fmt.Println("popped:", item)
}
}Map also provides Extract to read and delete a key, Keys to copy the
current keys, and Yield to iterate over key/value pairs. Slice provides
All and Extract to copy its contents, Index to read one position, and
SetChecked to write or extend the slice while checking whether the index was
accepted.
Both Yield methods return Go iterators and can be used with range, as shown
in the quick-start example.
Control is a context-aware semaphore. Acquire waits for a slot or context
cancellation. Release the slot after successful acquisition:
func process(ctx context.Context) {
control := syncing.NewControl(4)
if control.Acquire(ctx) {
defer control.Release()
fmt.Println("processing one job")
}
}Import context, fmt, and go.osspkg.com/syncing for this example.
Funnel serializes callbacks with the same key. Calls using different keys can
run concurrently:
func updateAccount() {
funnel := syncing.NewFunnel[string]()
funnel.Valve("account:42", func() {
fmt.Println("update account 42")
})
}Import fmt and go.osspkg.com/syncing for this example.
Group runs functions with a shared context. Background starts a goroutine;
Run runs the function synchronously while including it in the group's wait
count. Wait waits for work to finish. Cancel cancels the shared context and
then waits for all tracked functions.
func waitForWorker() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
group := syncing.NewGroup(ctx)
group.Background("worker", func(ctx context.Context) {
<-ctx.Done()
})
group.Cancel() // signal the worker to stop, then wait for it
}Import context and go.osspkg.com/syncing for this example.
Register group.OnPanic(func(err error) { ... }) to receive recovered
panics from Background and Run callbacks.
Limiter issues up to count tokens per interval. Tap waits for a token or
returns when its context is canceled. Cancel the constructor context to stop
the limiter's background refill loop.
func sendLimitedRequest() {
serviceCtx, stopService := context.WithCancel(context.Background())
defer stopService()
limiter := syncing.NewLimiter(serviceCtx, 5, time.Second)
requestCtx, cancelRequest := context.WithTimeout(context.Background(), 200*time.Millisecond)
defer cancelRequest()
if limiter.Tap(requestCtx) {
fmt.Println("send request")
}
}Import context, fmt, time, and go.osspkg.com/syncing for this example.
The circuitbreaker subpackage limits concurrent calls, applies a timeout to
each callback, and opens the circuit after the configured number of failures.
After Timeout, it allows one probe call to determine whether the dependency
has recovered.
import (
"context"
"errors"
"fmt"
"time"
circuitbreaker "go.osspkg.com/syncing/circuit-breaker"
)
func callWithBreaker() {
ctx := context.Background()
breaker := circuitbreaker.New(circuitbreaker.Config{
MaxParallel: 8,
Threshold: 3,
Timeout: 2 * time.Second,
})
err := breaker.Execute(ctx, func(context.Context) error {
return nil // replace with the dependency call
})
if errors.Is(err, circuitbreaker.ErrCircuitOpen) {
fmt.Println("the breaker is waiting before its next probe")
}
}NewLockandNewXLock[T]run callbacks under read or write locks.XLockreturns the callback's value and error.NewSwitchprovides atomicOn,Off,IsOn, andIsOffoperations.
func readConfig() (string, error) {
lock := syncing.NewXLock[string]()
return lock.RLock(func() (string, error) {
return "ready", nil
})
}Import go.osspkg.com/syncing for this example.
Run the Go test suite from the repository root:
go test ./...The GitHub Actions workflow runs make ci for the full project checks.
This project is distributed under the BSD 3-Clause License.