1
0
Fork 0
forked from External/ergo

add AcquireWithTimeout for semaphores

This commit is contained in:
Shivaram Lingamneni 2019-05-20 16:24:09 -04:00
parent b9b51625e1
commit dbf03d5c5e
2 changed files with 69 additions and 0 deletions

View file

@ -1,10 +1,12 @@
// Copyright (c) 2018 Shivaram Lingamneni
// released under the MIT license
package utils
import (
"log"
"runtime/debug"
"time"
)
// Semaphore is a counting semaphore. Note that a capacity of n requires O(n) storage.
@ -35,6 +37,25 @@ func (semaphore *Semaphore) TryAcquire() (acquired bool) {
}
}
// 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
}
// Release releases a semaphore. It never blocks. (This is not a license
// to program spurious releases.)
func (semaphore *Semaphore) Release() {