Add concurrency
This commit is contained in:
@@ -0,0 +1,40 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
var cities = []string{
|
||||
"Chicago",
|
||||
"Dallas",
|
||||
"Houston",
|
||||
"Los Angeles",
|
||||
"New York",
|
||||
"Philadelphia",
|
||||
"Phoenix",
|
||||
"San Antonio",
|
||||
"San Diego",
|
||||
"San Jose",
|
||||
}
|
||||
|
||||
func main() {
|
||||
now := time.Now()
|
||||
|
||||
printTemperatures(cities)
|
||||
|
||||
fmt.Printf(
|
||||
"\nTook %v to get temperatures sequentially.\n\n",
|
||||
time.Since(now),
|
||||
)
|
||||
|
||||
// Reset the timer.
|
||||
now = time.Now()
|
||||
|
||||
printTemperaturesAsync(cities)
|
||||
|
||||
fmt.Printf(
|
||||
"\nTook %v to get temperatures concurrently.\n\n",
|
||||
time.Since(now),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sync"
|
||||
|
||||
"github.com/dwrz/talks/concurrency/pkg/weather"
|
||||
)
|
||||
|
||||
const (
|
||||
// Hardcoded padding for longest city name, Philadelphia.
|
||||
message = "%-12s %.2f°F\n"
|
||||
)
|
||||
|
||||
func printTemperatures(cities []string) {
|
||||
for _, city := range cities {
|
||||
cityWeather, err := weather.GetCity(city)
|
||||
if err != nil {
|
||||
fmt.Printf(
|
||||
"error getting weather for %s: %v\n", city, err,
|
||||
)
|
||||
continue
|
||||
}
|
||||
|
||||
fmt.Printf(message, city, cityWeather.Temp)
|
||||
}
|
||||
}
|
||||
|
||||
func printTemperaturesAsync(cities []string) {
|
||||
var weatherReports = make(chan string, len(cities))
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(len(cities))
|
||||
|
||||
for _, city := range cities {
|
||||
go func(city string) {
|
||||
defer wg.Done()
|
||||
|
||||
cityWeather, err := weather.GetCity(city)
|
||||
if err != nil {
|
||||
fmt.Printf(
|
||||
"error getting weather for %s: %v\n",
|
||||
city, err,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
weatherReports <- fmt.Sprintf(
|
||||
message, city, cityWeather.Temp,
|
||||
)
|
||||
}(city)
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
close(weatherReports)
|
||||
|
||||
for report := range weatherReports {
|
||||
fmt.Print(report)
|
||||
}
|
||||
}
|
||||
Executable
+5
@@ -0,0 +1,5 @@
|
||||
#!/bin/bash
|
||||
|
||||
export OPEN_WEATHER_MAP_API_KEY="$(pass open-weather-map/api-key)"
|
||||
|
||||
go run ./*.go
|
||||
Reference in New Issue
Block a user