Created
June 18, 2016 03:52
-
-
Save montanaflynn/3692047f02fe06b90543a261bdb64783 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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