A very simple semaphore using channels.
go get -u -d github.com/codingconcepts/semaphore
The following example kicks off 1,000,000 goroutines, each of which increment a sum
variable atomically. After all operations have been kicked off, we ask the semaphore to wait for them to complete.
sum := int64(0)
sem := semaphore.New(10)
for i := 0; i < 1000000; i++ {
sem.Run(func() {
atomic.AddInt64(&sum, 1)
})
}
sem.Wait()
fmt.Println(sum)
// Prints: 1,000,000
Note that if you call Wait()
before all operations have been kicked off (and don't call it again at the end), the result of sum
is not guaranteed.