Skip to content

Instantly share code, notes, and snippets.

@pwaller
Created July 28, 2016 09:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pwaller/80e7843a490ac81e36f9c85b9f0b9439 to your computer and use it in GitHub Desktop.
Save pwaller/80e7843a490ac81e36f9c85b9f0b9439 to your computer and use it in GitHub Desktop.
A go worker pattern
token := make(chan struct{}, 1)
token <- struct{}{} // A goroutine must have the token to print
for test := range readTests(os.Stdin) {
gate <- struct{}{}
next := make(chan struct{}, 1) // where to send the token to.
go func(test Test, in, out chan struct{}) {
defer func() { <-gate }()
// Asynchronous work.
time.Sleep(1 * time.Second)
// This bit enforces running in the order we started
t := <-in // wait for token to become available
defer func() {
out <- t // give token to next worker
}()
// Runs in serial, in input order.
log.Printf("Ran %v", test)
}(test, token, next)
token = next // becomes the next token.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment