3
0
mirror of https://github.com/ergochat/ergo.git synced 2024-11-30 07:59:24 +01:00
ergo/irc/utils/semaphores.go

71 lines
1.6 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 (
"log"
"runtime/debug"
2019-05-20 22:24:09 +02:00
"time"
2019-04-15 17:13:13 +02:00
)
// Semaphore is a counting semaphore. Note that a capacity of n requires O(n) storage.
// A semaphore of capacity 1 can be used as a trylock.
type Semaphore (chan bool)
// Initialize initializes a semaphore to a given capacity.
func (semaphore *Semaphore) Initialize(capacity int) {
*semaphore = make(chan bool, capacity)
for i := 0; i < capacity; i++ {
(*semaphore) <- true
}
}
// Acquire acquires a semaphore, blocking if necessary.
func (semaphore *Semaphore) Acquire() {
<-(*semaphore)
}
// TryAcquire tries to acquire a semaphore, returning whether the acquire was
// successful. It never blocks.
func (semaphore *Semaphore) TryAcquire() (acquired bool) {
select {
case <-(*semaphore):
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 {
case <-(*semaphore):
acquired = true
case <-timer.C:
acquired = false
}
timer.Stop()
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 {
case (*semaphore) <- true:
// good
default:
// spurious release
log.Printf("spurious semaphore release (full to capacity %d)", cap(*semaphore))
debug.PrintStack()
}
}