Go · lesson 27 of 30 · Tools for the NASDo work side by side
WaitGroup.Go starts each goroutine, Wait waits for all of them and a channel limits how many work at once.
27-goroutines.go Download 27-goroutines.go
package main
import (
"crypto/sha256"
"fmt"
"os"
"path/filepath"
"sync"
)
func main() {
files, _ := filepath.Glob("photos/*")
sums := make([]string, len(files))
var wait sync.WaitGroup
slots := make(chan struct{}, 2) // two files at a time
for i, name := range files {
wait.Go(func() {
slots <- struct{}{}
defer func() { <-slots }()
data, err := os.ReadFile(name)
if err != nil {
sums[i] = err.Error()
return
}
sums[i] = fmt.Sprintf("%x", sha256.Sum256(data))[:12]
})
}
wait.Wait()
for i, name := range files {
fmt.Println(sums[i], name)
}
}
Terminal
$ ./27-goroutines
871d72a89ff3 photos/beach.jpg
fa807c957eaf photos/cat.jpg
8bffbf88a5b1 photos/garden.jpg
6edd9f6f9cc9 photos/notes.txt
fa2a0a858265 photos/trip.mp4
d3b12e65fa11 photos/wedding.movExercise
Print the total time with one and with four slots.
TurboShell does not contain Go. These programs are made in Bucket & Code with its Go runtime; the finished file runs on the NAS without Go.