github.com/openshift/installer@v1.4.17/pkg/destroy/openstack/semaphore.go (about) 1 package openstack 2 3 import "sync" 4 5 type semaphore struct { 6 semC chan struct{} 7 wg sync.WaitGroup 8 } 9 10 // newSemaphore returns a semaphore. A semaphore runs at most maxConcurrency 11 // functions concurrently. 12 func newSemaphore(maxConcurrency int) *semaphore { 13 return &semaphore{ 14 semC: make(chan struct{}, maxConcurrency), 15 } 16 } 17 18 // Add enqueues the function f to be run in a separate goroutine as soon as 19 // there is a free slot. Add returns immediately. 20 func (s *semaphore) Add(f func()) { 21 s.wg.Add(1) 22 go func() { 23 s.semC <- struct{}{} 24 defer func() { 25 <-s.semC 26 s.wg.Done() 27 }() 28 f() 29 }() 30 } 31 32 // Wait returns when the queue is empty and no function is running. 33 func (s *semaphore) Wait() { 34 s.wg.Wait() 35 }