Last active
September 29, 2020 06:01
-
-
Save ohookins/5013420 to your computer and use it in GitHub Desktop.
Worker Pool example in Go
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 | |
import ( | |
"fmt" | |
"net/http" | |
"os" | |
"sync" | |
) | |
var ( | |
requests = 10000 | |
concurrency = 200 | |
url = "http://localhost:3000/" | |
wait = sync.WaitGroup{} | |
) | |
func main() { | |
client := &http.Client{} | |
output := make(chan string) | |
for i := 0; i < concurrency; i++ { | |
go httpWorker(client, output) | |
} | |
for i := 0; i < requests; i++ { | |
output <- url | |
fmt.Printf("\r%d", i+1) | |
} | |
close(output) | |
fmt.Println("") | |
os.Stdout.Sync() | |
fmt.Println("All URLs handled.") | |
os.Stdout.Sync() | |
wait.Wait() | |
fmt.Println("All workers done.") | |
} | |
func httpWorker(client *http.Client, input chan string) { | |
// Increment the wait group counter | |
wait.Add(1) | |
// Iterate over channel input work | |
for req := range input { | |
if _, err := client.Head(req); err != nil { | |
fmt.Println(err) | |
} | |
} | |
// Finish up this worker | |
wait.Done() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment