Last active
June 22, 2024 12:01
-
-
Save lxwagn/b13f4c53eb8e2a681292514e207fc3fc to your computer and use it in GitHub Desktop.
Idiomatic semaphore example in Go (using Buffered Channels)
This file contains 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