Lock provides exclusive and shared locks for synchronizing access to resources inside one Go process or across services.
The package includes non-blocking and blocking acquisition, expiring locks,
ownership checks, transferable keys, shared read locks, quorum stores, local
file locks, and semantic adapters for common remote lock systems. It uses only
the Go standard library and keeps storage clients behind the LeaseBackend
interface.
The package requires Go 1.26 or newer.
go get github.com/lemric/lock-gopackage main
import (
"context"
"fmt"
"log"
lock "github.com/lemric/lock-go"
)
func main() {
store := lock.NewInMemoryStore()
factory := lock.NewFactory(store)
invoiceLock := factory.CreateDefault("invoice:INV-1001")
acquired, err := invoiceLock.Acquire(context.Background(), false)
if err != nil {
log.Fatal(err)
}
if !acquired {
fmt.Println("invoice is already being processed")
return
}
defer func() {
if err := invoiceLock.Close(); err != nil {
log.Printf("release invoice lock: %v", err)
}
}()
fmt.Println("processing invoice INV-1001")
}The resource string identifies what is protected. Two independently created
locks for the same resource have different owners, so only one can acquire an
exclusive lock at a time. Calling Acquire again on the same lock is
idempotent.
The second Acquire argument selects blocking behavior. false returns
immediately with acquired == false when another owner holds the resource;
true waits until acquisition succeeds or the context is canceled.
Go has no deterministic destructors. autoRelease therefore takes effect when
the application explicitly calls Close; use defer lock.Close() or call
Release directly.
- Documentation index
- Installation
- Getting started
- Blocking locks
- Expiring locks
- Shared locks
- Ownership and transferable keys
- Available stores
- Combined stores and quorum strategies
- Store factory and DSNs
- Custom lease backends
- Reliability
- Errors and logging
- Concurrency and guarantees
- API reference
go test ./...
go test -race ./...
go vet ./...This package is released under the MIT License.