ircd/irc/utils/semaphores.go

72 lines
1.7 KiB
Go
Raw Normal View History

2019-04-15 15:13:13 +00:00
// Copyright (c) 2018 Shivaram Lingamneni
2019-05-20 20:24:09 +00:00
// released under the MIT license
2019-04-15 15:13:13 +00:00
package utils
import (
2019-10-02 23:22:10 +00:00
"context"
2019-05-20 20:24:09 +00:00
"time"
2019-04-15 15:13:13 +00:00
)
2019-10-02 23:22:10 +00:00
// Semaphore is a counting semaphore.
2019-04-15 15:13:13 +00:00
// A semaphore of capacity 1 can be used as a trylock.
2020-08-05 01:46:16 +00:00
type Semaphore (chan empty)
2019-04-15 15:13:13 +00:00
// NewSemaphore creates and initializes a semaphore to a given capacity.
func NewSemaphore(capacity int) Semaphore {
return make(chan empty, capacity)
2019-04-15 15:13:13 +00:00
}
// Acquire acquires a semaphore, blocking if necessary.
func (semaphore Semaphore) Acquire() {
semaphore <- empty{}
2019-04-15 15:13:13 +00:00
}
// TryAcquire tries to acquire a semaphore, returning whether the acquire was
// successful. It never blocks.
func (semaphore Semaphore) TryAcquire() (acquired bool) {
2019-04-15 15:13:13 +00:00
select {
case semaphore <- empty{}:
2019-04-15 15:13:13 +00:00
return true
default:
return false
}
}
2019-05-20 20:24:09 +00: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) {
2019-05-20 20:24:09 +00:00
if timeout < 0 {
return semaphore.TryAcquire()
}
timer := time.NewTimer(timeout)
select {
case semaphore <- empty{}:
2019-05-20 20:24:09 +00:00
acquired = true
case <-timer.C:
acquired = false
}
timer.Stop()
return
}
2019-10-02 23:22:10 +00: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) {
2019-10-02 23:22:10 +00:00
select {
case semaphore <- empty{}:
2019-10-02 23:22:10 +00:00
acquired = true
case <-ctx.Done():
acquired = false
}
return
}
2021-04-07 12:33:19 +00:00
// Release releases a semaphore.
func (semaphore Semaphore) Release() {
<-semaphore
2019-04-15 15:13:13 +00:00
}