Skip to content

Instantly share code, notes, and snippets.

@gsquire
Last active March 22, 2018 21:31
Show Gist options
  • Save gsquire/0c474c0b65bb6c05e6bd3787842d9b3c to your computer and use it in GitHub Desktop.
Save gsquire/0c474c0b65bb6c05e6bd3787842d9b3c to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"sync"
"time"
)
var wg sync.WaitGroup
func printer(sem chan struct{}) {
defer wg.Done()
// An artificial sleep for simulating a long running operation.
time.Sleep(2 * time.Second)
fmt.Println("hello")
<-sem
}
func main() {
// A buffered channel only has enough room for 2 items in this case.
sem := make(chan struct{}, 2)
wg.Add(10)
for i := 0; i < 10; i++ {
// "Enqueue" our work and fire off a goroutine.
// This will block when our channel becomes full.
sem <- struct{}{}
// This won't fire until our channel releases in `printer()`.
go printer(sem)
}
wg.Wait()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment