https://github.com/werbenhu/keylock
A simple, high-performance key-based locking mechanism for Go.
https://github.com/werbenhu/keylock
Last synced: about 2 months ago
JSON representation
A simple, high-performance key-based locking mechanism for Go.
- Host: GitHub
- URL: https://github.com/werbenhu/keylock
- Owner: werbenhu
- Created: 2025-06-09T09:56:40.000Z (4 months ago)
- Default Branch: master
- Last Pushed: 2025-06-11T12:24:18.000Z (4 months ago)
- Last Synced: 2025-06-11T13:40:32.458Z (4 months ago)
- Language: Go
- Homepage:
- Size: 3.91 KB
- Stars: 0
- Watchers: 0
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# KeyLock
A simple, high-performance key-based locking mechanism for Go.
## Features
- Lock by string key for fine-grained synchronization
- High performance with spinlocks and atomic operations## Installation
```bash
go get github.com/werbenhu/keylock
```## Usage
### Basic Example
```go
package mainimport "github.com/werbenhu/keylock"
func main() {
kl := keylock.New()
// Lock a resource by key
kl.Lock("user:123")
// ... critical section ...
kl.Unlock("user:123")
}
```### Try Lock (Non-blocking)
```go
if kl.TryLock("resource") {
defer kl.Unlock("resource")
// ... do work ...
} else {
// Lock is busy, handle accordingly
}
```## API
| Method | Description |
|--------|-------------|
| `New()` | Create a new KeyLock |
| `Lock(key)` | Acquire lock for key (blocks) |
| `TryLock(key)` | Try to acquire lock (returns bool) |
| `Unlock(key)` | Release lock for key |
| `Size()` | Number of active locks |
| `Cleanup()` | Remove unused locks from memory |
| `WithMaxSpins(n)` | Set max spin attempts |## Configuration
```go
// Default configuration
kl := keylock.New()// Custom spin limit
kl := keylock.New().WithMaxSpins(32)
```