3
0
mirror of https://github.com/ergochat/ergo.git synced 2024-12-23 19:22:41 +01:00
ergo/irc/utils/semaphores.go

84 lines
2.0 KiB
Go
Raw Normal View History

2019-04-15 17:13:13 +02:00
// Copyright (c) 2018 Shivaram Lingamneni
2019-05-20 22:24:09 +02:00
// released under the MIT license
2019-04-15 17:13:13 +02:00
package utils
import (
2019-10-03 01:22:10 +02:00
"context"
2019-04-15 17:13:13 +02:00
"log"
"runtime/debug"
2019-05-20 22:24:09 +02:00
"time"
2019-04-15 17:13:13 +02:00
)
2019-10-03 01:22:10 +02:00
type e struct{}
// Semaphore is a counting semaphore.
2019-04-15 17:13:13 +02:00
// A semaphore of capacity 1 can be used as a trylock.
2019-10-03 01:22:10 +02:00
type Semaphore (chan e)
2019-04-15 17:13:13 +02:00
// Initialize initializes a semaphore to a given capacity.
func (semaphore *Semaphore) Initialize(capacity int) {
2019-10-03 01:22:10 +02:00
*semaphore = make(chan e, capacity)
2019-04-15 17:13:13 +02:00
}
// Acquire acquires a semaphore, blocking if necessary.
func (semaphore *Semaphore) Acquire() {
2019-10-03 01:22:10 +02:00
(*semaphore) <- e{}
2019-04-15 17:13:13 +02:00
}
// TryAcquire tries to acquire a semaphore, returning whether the acquire was
// successful. It never blocks.
func (semaphore *Semaphore) TryAcquire() (acquired bool) {
select {
2019-10-03 01:22:10 +02:00
case (*semaphore) <- e{}:
2019-04-15 17:13:13 +02:00
return true
default:
return false
}
}
2019-05-20 22:24:09 +02:00
// AcquireWithTimeout tries to acquire a semaphore, blocking for a maximum
// of approximately `d` while waiting for it. It returns whether the acquire
// was successful.
func (semaphore *Semaphore) AcquireWithTimeout(timeout time.Duration) (acquired bool) {
if timeout < 0 {
return semaphore.TryAcquire()
}
timer := time.NewTimer(timeout)
select {
2019-10-03 01:22:10 +02:00
case (*semaphore) <- e{}:
2019-05-20 22:24:09 +02:00
acquired = true
case <-timer.C:
acquired = false
}
timer.Stop()
return
}
2019-10-03 01:22:10 +02:00
// AcquireWithContext tries to acquire a semaphore, blocking at most until
// the context expires. It returns whether the acquire was successful.
// Note that if the context is already expired, the acquire may succeed anyway.
func (semaphore *Semaphore) AcquireWithContext(ctx context.Context) (acquired bool) {
select {
case (*semaphore) <- e{}:
acquired = true
case <-ctx.Done():
acquired = false
}
return
}
2019-04-15 17:13:13 +02:00
// Release releases a semaphore. It never blocks. (This is not a license
// to program spurious releases.)
func (semaphore *Semaphore) Release() {
select {
2019-10-03 01:22:10 +02:00
case <-(*semaphore):
2019-04-15 17:13:13 +02:00
// good
default:
// spurious release
log.Printf("spurious semaphore release (full to capacity %d)", cap(*semaphore))
debug.PrintStack()
}
}