Created
January 31, 2020 13:56
-
-
Save muhlemmer/6be45df7b325d47c70a96bb23ce85c3e to your computer and use it in GitHub Desktop.
A small example used for presentations on Go routines.
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
package main | |
/* | |
Run with: | |
go run main.go | |
Flags: | |
-number int | |
Number of requests (default 10) | |
-wait int | |
Max wait for requests (default 100) | |
*/ | |
import ( | |
"flag" | |
"fmt" | |
"log" | |
"math/rand" | |
"sync" | |
"time" | |
) | |
// Request simulates an I/O operation by randomly waiting up to `w` milliseconds | |
func Request(w int64) string { | |
d := time.Duration(rand.Int63n(w)) * time.Millisecond | |
time.Sleep(d) | |
return fmt.Sprintf("Blocked for %v", d) | |
} | |
// SerialWorkers runs `n` amount of requests and logs the outputs. | |
// When all requests are done, it logs the total time taken. | |
// `w` is the maximum random wait time passed to each request. | |
func SerialWorkers(n int, w int64) { | |
s := time.Now() | |
for i := 0; i < n; i++ { | |
log.Printf("Req #%02d done: %s", i, Request(w)) | |
} | |
log.Printf("%s: Requests completed after %v", "SerialWorkers", time.Now().Sub(s)) | |
} | |
// ConcurrentWorkers does the same thing as SerialWorkers, | |
// only each request is run in a separate Go routine. | |
// It waits until all routines are finished | |
func ConcurrentWorkers(n int, w int64) { | |
s := time.Now() | |
var wg sync.WaitGroup | |
wg.Add(n) | |
for i := 0; i < n; i++ { | |
go func(i int) { | |
log.Printf("Req #%02d done: %s", i, Request(w)) | |
wg.Done() | |
}(i) | |
} | |
wg.Wait() | |
log.Printf("%s: Requests completed after %v", "ConcurrentWorkers", time.Now().Sub(s)) | |
} | |
var ( | |
number int | |
maxWait int64 | |
) | |
func init() { | |
flag.IntVar(&number, "number", 10, "Number of requests") | |
flag.Int64Var(&maxWait, "wait", 100, "Max wait for requests") | |
flag.Parse() | |
} | |
func main() { | |
log.Println("Running SerialWorkers") | |
SerialWorkers(number, maxWait) | |
log.Println("-------------------------") | |
log.Println("Running ConcurrentWorkers") | |
ConcurrentWorkers(number, maxWait) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example output: