зеркало из https://github.com/github/vitess-gh.git
sync2: add TryAcquire to Semaphore
This commit is contained in:
Родитель
b70c235f68
Коммит
4a43bb7839
|
@ -49,6 +49,17 @@ func (sem *Semaphore) Acquire() bool {
|
|||
}
|
||||
}
|
||||
|
||||
// TryAcquire acquires a semaphore if it's immediately available.
|
||||
// It returns false otherwise.
|
||||
func (sem *Semaphore) TryAcquire() bool {
|
||||
select {
|
||||
case <-sem.slots:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// Release releases the acquired semaphore. You must
|
||||
// not release more than the number of semaphores you've
|
||||
// acquired.
|
||||
|
|
|
@ -20,7 +20,7 @@ func TestSemaNoTimeout(t *testing.T) {
|
|||
}()
|
||||
s.Acquire()
|
||||
if !released {
|
||||
t.Errorf("want true, got false")
|
||||
t.Errorf("release: false, want true")
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -31,11 +31,25 @@ func TestSemaTimeout(t *testing.T) {
|
|||
time.Sleep(10 * time.Millisecond)
|
||||
s.Release()
|
||||
}()
|
||||
if ok := s.Acquire(); ok {
|
||||
t.Errorf("want false, got true")
|
||||
if s.Acquire() {
|
||||
t.Errorf("Acquire: true, want false")
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
if ok := s.Acquire(); !ok {
|
||||
t.Errorf("want true, got false")
|
||||
if !s.Acquire() {
|
||||
t.Errorf("Acquire: false, want true")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSemaTryAcquire(t *testing.T) {
|
||||
s := NewSemaphore(1, 0)
|
||||
if !s.TryAcquire() {
|
||||
t.Errorf("TryAcquire: false, want true")
|
||||
}
|
||||
if s.TryAcquire() {
|
||||
t.Errorf("TryAcquire: true, want false")
|
||||
}
|
||||
s.Release()
|
||||
if !s.TryAcquire() {
|
||||
t.Errorf("TryAcquire: false, want true")
|
||||
}
|
||||
}
|
||||
|
|
Загрузка…
Ссылка в новой задаче