Created
July 28, 2016 09:57
-
-
Save pwaller/80e7843a490ac81e36f9c85b9f0b9439 to your computer and use it in GitHub Desktop.
A go worker pattern
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
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