Add concurrency

This commit is contained in:
dwrz
2026-10-27 12:41:06 +00:00
commit 2334f4eaf0
31 changed files with 43061 additions and 0 deletions
+40
View File
@@ -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),
)
}
+59
View File
@@ -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)
}
}
+5
View File
@@ -0,0 +1,5 @@
#!/bin/bash
export OPEN_WEATHER_MAP_API_KEY="$(pass open-weather-map/api-key)"
go run ./*.go