Bläddra i källkod

Semaphore empty check added

Sudersen Archakam 8 år sedan
förälder
incheckning
ad13f17c97
2 ändrade filer med 25 tillägg och 0 borttagningar
  1. 5 0
      semaphore/semaphore.go
  2. 20 0
      semaphore/semaphore_test.go

+ 5 - 0
semaphore/semaphore.go

@@ -43,3 +43,8 @@ func (s *Semaphore) Acquire() error {
 func (s *Semaphore) Release() {
 	<-s.sem
 }
+
+// IsEmpty would return true if none acquired ar that moment of time, otherwise false.
+func (s *Semaphore) IsEmpty() bool {
+	return len(s.sem) == 0
+}

+ 20 - 0
semaphore/semaphore_test.go

@@ -45,6 +45,26 @@ func TestSemaphoreBlockTimeout(t *testing.T) {
 	}
 }
 
+func TestSemaphoreEmpty(t *testing.T) {
+	sem := New(2, 200*time.Millisecond)
+
+	if !sem.IsEmpty() {
+		t.Error("semaphore should be empty")
+	}
+
+	sem.Acquire()
+
+	if sem.IsEmpty() {
+		t.Error("semaphore should not be empty")
+	}
+
+	sem.Release()
+
+	if !sem.IsEmpty() {
+		t.Error("semaphore should be empty")
+	}
+}
+
 func ExampleSemaphore() {
 	sem := New(3, 1*time.Second)