Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/tlkamp/go-semaphore
A resizable semaphore implementation for Golang.
https://github.com/tlkamp/go-semaphore
concurrency go golang semaphore
Last synced: 11 days ago
JSON representation
A resizable semaphore implementation for Golang.
- Host: GitHub
- URL: https://github.com/tlkamp/go-semaphore
- Owner: tlkamp
- License: mit
- Created: 2023-11-21T02:43:03.000Z (12 months ago)
- Default Branch: main
- Last Pushed: 2024-08-10T22:38:08.000Z (3 months ago)
- Last Synced: 2024-08-11T16:36:55.102Z (3 months ago)
- Topics: concurrency, go, golang, semaphore
- Language: Go
- Homepage:
- Size: 12.7 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- License: LICENSE
Awesome Lists containing this project
README
[![Go Report Card](https://goreportcard.com/badge/github.com/tlkamp/go-semaphore)](https://goreportcard.com/report/github.com/tlkamp/go-semaphore)
![testworkflow](https://github.com/tlkamp/go-semaphore/actions/workflows/test.yaml/badge.svg?branch=main)# Resizable Semaphore
A resizable semaphore for Golang.
Inspired by and possible due to https://github.com/eapache/channels.
## Feature Overview
- Conforms to typical semaphore interfaces
- Semaphore can be resized, up or down, at runtime## Example
### General Usage
```go
package mainimport (
"context"
"fmt"
"sync"
"time""github.com/tlkamp/go-semaphore"
)func main() {
sem := semaphore.New(2)
wg := &sync.WaitGroup{}for i := 0; i <= 10; i++ {
err := sem.Acquire(context.Background())
if err != nil {
fmt.Println(err)
return
}wg.Add(1)
go func(n int) {
defer sem.Release()
defer wg.Done()time.Sleep(3 * time.Second)
fmt.Printf("Processed: %d\n", n)
}(i)
}wg.Wait()
fmt.Println("Complete")
}
```### Resize the Semaphore
```go
package mainimport (
"context"
"fmt"
"sync"
"time""github.com/tlkamp/go-semaphore"
)func longFn(i int) {
time.Sleep(200 * time.Millisecond)
fmt.Printf("Processed: %d\n", i)
}func main() {
sem := semaphore.New(1)
wg := &sync.WaitGroup{}// Set a timer and then increase the semaphore substantially
go func() {
time.Sleep(3 * time.Second)
sem.Resize(10)
fmt.Printf("===> Resized to %d\n", sem.Cap())
}()for i := 0; i <= 100; i++ {
err := sem.Acquire(context.Background())
if err != nil {
fmt.Println(err)
return
}wg.Add(1)
go func(n int) {
defer sem.Release()
defer wg.Done()longFn(n)
}(i)
}wg.Wait()
fmt.Println("Complete")
}```
## Contribute
Contributions are accepted in the form of issues and PRs.PRs must have:
- Test cases
- Documentation
- Example (if applicable)