github.com/abiosoft/semaphore@v0.0.0-20240818083615-bc6b5b10c137/semaphore_test.go (about) 1 package semaphore 2 3 import ( 4 "fmt" 5 "sync" 6 "testing" 7 "time" 8 ) 9 10 var done = make(chan int, 3) 11 var g = &sync.WaitGroup{} 12 13 func Test(t *testing.T) { 14 l := 7 15 s := New(10) 16 for i := 0; i < l; i++ { 17 g.Add(1) 18 go aq(s, i+1) 19 } 20 go func() { 21 g.Add(1) 22 if s.AcquireWithin(5, time.Second*3) { 23 s.ReleaseMany(5) 24 fmt.Println("Acquired within") 25 } else { 26 fmt.Println("Acquire timeout") 27 } 28 g.Done() 29 }() 30 g.Wait() 31 if n := s.DrainPermits(); n != 10 { 32 t.Fail() 33 s.ReleaseMany(n) 34 } else { 35 s.ReleaseMany(10) 36 } 37 } 38 39 func aq(s *Semaphore, i int) { 40 fmt.Println("Waiting to acquire", i, "permits, avail:", s.AvailablePermits()) 41 s.AcquireMany(i) 42 fmt.Println("Acquired", i, "permits, avail:", s.AvailablePermits()) 43 time.Sleep(time.Second * 3) 44 s.ReleaseMany(i) 45 fmt.Println("Done. Released", i, "permits, avail:", s.AvailablePermits()) 46 g.Done() 47 }