Skip to content

Instantly share code, notes, and snippets.

@montanaflynn
Created June 18, 2016 03:52
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save montanaflynn/3692047f02fe06b90543a261bdb64783 to your computer and use it in GitHub Desktop.
Save montanaflynn/3692047f02fe06b90543a261bdb64783 to your computer and use it in GitHub Desktop.
package semaphore
// Semaphore channel
type Semaphore chan struct{}
// Acquire resource
func (s Semaphore) Acquire() {
s <- struct{}{}
}
// Release resource
func (s Semaphore) Release() {
<-s
}
// Wait for completion
func (s Semaphore) Wait() {
for i := 0; i < cap(s); i++ {
s <- struct{}{}
}
}
// Run `fn` in a goroutine, acquiring then releasing after its return
func (s Semaphore) Run(fn func()) {
s.Acquire()
go func() {
defer s.Release()
fn()
}()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment