Last active
March 22, 2018 21:31
-
-
Save gsquire/0c474c0b65bb6c05e6bd3787842d9b3c 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 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