https://github.com/xaionaro-go/lockmap
A map of lockers
https://github.com/xaionaro-go/lockmap
go golang lock locker lockmap map variable
Last synced: about 1 year ago
JSON representation
A map of lockers
- Host: GitHub
- URL: https://github.com/xaionaro-go/lockmap
- Owner: xaionaro-go
- License: bsd-3-clause
- Created: 2024-08-12T23:47:49.000Z (over 1 year ago)
- Default Branch: main
- Last Pushed: 2024-09-01T17:28:18.000Z (over 1 year ago)
- Last Synced: 2025-01-10T02:44:49.605Z (over 1 year ago)
- Topics: go, golang, lock, locker, lockmap, map, variable
- Language: Go
- Homepage:
- Size: 5.86 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# LockMap
[](https://pkg.go.dev/github.com/xaionaro-go/lockmap?tab=doc)
# Motivation
This is a recurrent pattern I met in different situations. For example:
* When we need to process an HTTP request if the result is cacheable: we want to wait one request to finish and then to copy the result to everybody who requested it.
* When we need to allow only one goroutine to send a request out (which depends on variables).
* etc.
# Quick start
Synchronous locking:
```go
lm := lockmap.New()
...
ctx := context.Background()
unlocker := lm.Lock(ctx, "key1")
defer unlocker.Unlock(ctx, "key1")
// do something with key1
```
Asynchronous locking:
```go
lm := lockmap.New()
...
ctx, cancelFn := context.WithTimeout(context.Background(), time.Second*30)
defer cancelFn()
unlocker, waiter := lm.LockAsync(ctx, "key1")
defer unlocker.Unlock("key1")
select {
case <-waiter.C:
if !unlocker.IsLocked() {
// reached 30sec timeout
return
}
// do something with key1
case <-someOtherChan:
// do something else
}
```