-
-
Save geordee/d5469fa428a4a2d69dabb15a57794276 to your computer and use it in GitHub Desktop.
Idiomatic semaphore example in Go (using Buffered Channels)
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
// Idiomatic Semaphore Example in Go | |
// Lucas Wagner | |
// Golang has no built-in facility to implement semaphores, so a common design | |
// pattern is to use buffered channels. | |
package main | |
import ( | |
"fmt" | |
"time" | |
) | |
func printIt(sem chan bool, msg string, iter int){ | |
// release the resource when we're done | |
defer func () { <-sem } () | |
fmt.Println(msg, " ", iter) | |
} | |
func main() { | |
resourcePool := 3 | |
sem := make(chan bool, resourcePool) | |
for i := 0 ; i < 10 ; i++ { | |
// pause for the scheduler | |
time.Sleep(100 * time.Millisecond) | |
// acquire a single resource | |
sem <- true | |
go printIt(sem, "Test ", i) | |
} | |
// acquire the resources back; then we know it's done | |
for j := 0 ; j < resourcePool ; j++ { | |
sem <- true | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment